Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get total for limit in mysql using same query?

Tags:

mysql

limit

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
like image 991
TDSii Avatar asked Mar 11 '11 23:03

TDSii


People also ask

How do you get the total records even if LIMIT is applied?

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.

How can we get total number of records by query in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query. Note: NULL values are not counted.

Does MySQL allow the use of order by and LIMIT in the same query?

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.

How do you count limits in SQL?

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.


1 Answers

No one really mentions this, but the correct way of using the SQL_CALC_FOUND_ROWS technique is like this:

  1. Perform your query: SELECT SQL_CALC_FOUND_ROWS * FROM `table` LIMIT 0, 10
  2. Then run this query directly afterwards: 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.
like image 97
silkfire Avatar answered Oct 23 '22 09:10

silkfire