简体   繁体   中英

get total for limit in mysql using same query?

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

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, ie as if you hadn't used the LIMIT clause. This second query is instantly fast, because the result has already been cached.

You can do it with a subquery :

select 
    *,
    (select count(*) from mytable) as total
from mytable LIMIT 0,10

But I don't think this has any kind of advantage.

edit: Like Ilya said, the total count and the rows have a totally different meaning, there's no real point in wanting to retrieve these data in the same query. I'll stick with the two queries. I just gave this answer for showing that this is possible, not that it is a good idea.

While i've seen some bad approaches to this, when i have looked into this previously there were two commonly accepted solutions:

  1. Running your query and then running the same query with a count as you have done in your question.

  2. Run your query and then run it again with the SQL_CALC_FOUND_ROWS keyword.

eg. SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 0,10

This second approach is how phpMyAdmin does it.

You can run the first query and then the second query, and so you'll get both the count and the first results.

A query returns a set of records. The count is definitely not one of the records a "SELECT *" query can return, because there is only one count for the entire result set.

Anyway, you didn't say what programming language you run these SQL queries from and what interface you're using. Maybe this option exists in the interface.

SELECT SQL_CALC_FOUND_ROWS your query here Limit ...

Without running any other queries or destroying the session then run SELECT FOUND_ROWS();

And you will get the total count of rows

The problem with 2 queries is consistency. In the time between the 2 queries the data may be changed. If your logic depends on what is counted has to be returned then your only approach would be to use SQL_CALC_FOUND_ROWS.

As of Mysql 8.0.17 SQL_CALC_FOUND_ROWS and FOUND_ROWS() will be deprecated. I don't know of a consistent solution after this functionality has been removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM