MySQL: Get total number of rows when using LIMIT
A
SELECT
statement may include a LIMIT
clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT
, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS
option in theSELECT
statement, and then invoke FOUND_ROWS()
afterward:mysql>SELECT SQL_CALC_FOUND_ROWS * FROM
->tbl_name
WHERE id > 100 LIMIT 10;
mysql>SELECT FOUND_ROWS();
The second
SELECT
returns a number indicating how many rows the first SELECT
would have returned had it been written without the LIMIT
clause.
In the absence of the
SQL_CALC_FOUND_ROWS
option in the most recent successful SELECT
statement,FOUND_ROWS()
returns the number of rows in the result set returned by that statement. If the statement includes aLIMIT
clause, FOUND_ROWS()
returns the number of rows up to the limit. For example, FOUND_ROWS()
returns 10 or 60, respectively, if the statement includes LIMIT 10
or LIMIT 50, 10
.
The row count available through
FOUND_ROWS()
is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS
statement. If you need to refer to the value later, save it:mysql>SELECT SQL_CALC_FOUND_ROWS * FROM ... ;
mysql>SET @rows = FOUND_ROWS();
If you are using
SELECT SQL_CALC_FOUND_ROWS
, MySQL must calculate how many rows are in the full result set. However, this is faster than running the query again without LIMIT
, because the result set need not be sent to the client.SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS()
enables you to determine how many other pages are needed for the rest of the result.
The use of
SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
is more complex for UNION
statements than for simpleSELECT
statements, because LIMIT
may occur at multiple places in a UNION
. It may be applied to individualSELECT
statements in the UNION
, or global to the UNION
result as a whole.
The intent of
SQL_CALC_FOUND_ROWS
for UNION
is that it should return the row count that would be returned without a global LIMIT
. The conditions for use of SQL_CALC_FOUND_ROWS
with UNION
are:- The value of
FOUND_ROWS()
is exact only ifUNION ALL
is used. IfUNION
withoutALL
is used, duplicate removal occurs and the value ofFOUND_ROWS()
is only approximate.
No comments:
Post a Comment