I am making a pagination method, what i did was: First query will count all results and the second query will do the normal select with LIMIT
Is there technically any way to do this what I've done, but with only one query?
What I have now:
SELECT count(*) from table
SELECT * FROM table LIMIT 0,10
Since MYSQL 4.0 we can use SQL_CALC_FOUND_ROWS option in query which will tell MySQL to count total number of rows disregarding LIMIT clause. In main query add SQL_CALC_FOUND_ROWS option just after SELECT and in second query use FOUND_ROWS() function to get total number of rows without executing the query.
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query. Note: NULL values are not counted.
In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.
The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the number of records returned based on a limit value. TIP: SELECT LIMIT is not supported in all SQL databases. For databases such as SQL Server or MSAccess, use the SELECT TOP statement to limit your results.
No one really mentions this, but the correct way of using the SQL_CALC_FOUND_ROWS
technique is like this:
SELECT SQL_CALC_FOUND_ROWS * FROM `table` LIMIT 0, 10
SELECT FOUND_ROWS()
. The result of this query contains the full count of the previous query, i.e. as if you hadn't used the LIMIT
clause. This second query is instantly fast, because the result has already been cached.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With