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
While i've seen some bad approaches to this, when i have looked into this previously there were two commonly accepted solutions:
Running your query and then running the same query with a
count
as you have done in your question.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.
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 theLIMIT
clause. This second query is instantly fast, because the result has already been cached.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
You can do it with a subquery :
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.