get total for limit in mysql using same query?

2019-01-23 08:20发布

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

标签: mysql limit
5条回答
叛逆
2楼-- · 2019-01-23 08:49

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-23 08:52

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.
查看更多
孤傲高冷的网名
4楼-- · 2019-01-23 08:55

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.

查看更多
叼着烟拽天下
5楼-- · 2019-01-23 08:57

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

查看更多
相关推荐>>
6楼-- · 2019-01-23 09:03

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.

查看更多
登录 后发表回答