Find total number of results in mySQL query with offset+limit
Take a look at SQL_CALC_FOUND_ROWS
SELECT COUNT(*) FROM table_name WHERE column = 'value'
will return the total number of records in a table matching that condition very quickly.
Database SELECT
operations are usually "cheap" (resource-wise), so don't feel too bad about using them in a reasonable manner.
EDIT: Added WHERE
after the OP mentioned that they need that feature.
Considering that SQL_CALC_FOUND_ROWS requires invoking FOUND_ROWS()
afterwards, if you wanted to fetch the total count with the results returned from your limit without having to invoke a second SELECT
, I would use JOIN results derived from a subquery:
SELECT * FROM `table` JOIN (SELECT COUNT(*) FROM `table` WHERE `category_id` = 9) t2 WHERE `category_id` = 9 LIMIT 50
Note: Every derived table must have its own alias, so be sure to name the joined table. In my example I used t2
.