I’m trying to write a mysql query such that I can retreieve the first 10 rows of a table and get the total row count in the same query.
i.e. combine
SELECT * FROM myTable LIMIT 10; // Get First 10 Rows
and
SELECT COUNT(*) as cnt FROM myTable // Total Row Count
in the same query.
Since I’m using PHP, technically I could execute :
SELECT * FROM myTable
Then use count() to get total row count and array_slice to get first 10 array elements.
But that doesn’t sound very efficient.
It’s not exactly in one query, but the second query is always the same and it won’t have to execute the complete previous query again, which is good if it is a complex query.
It’s the
SQL_CALC_FOUND_ROWSclause in the first query that causes the total number of records to be calculated as if the limit wasn’t added.