MySQL Pagination: Efficiently Retrieving Results and Total Count
When implementing pagination in MySQL, it's common practice to perform two separate queries: one to get the total number of results and another to limit the fetched records. This approach, known as double-querying, can be inefficient for large datasets.
However, the question arises whether it's possible to retrieve both the total result count and limit the results in a single query. While there is no direct way to achieve this, two alternative methods are available:
SQL_CALC_FOUND_ROWS and FOUND_ROWS()
Instead of double-querying, you can utilize the SQL_CALC_FOUND_ROWS and FOUND_ROWS() functions to achieve a similar result. The query with SQL_CALC_FOUND_ROWS precedes the limiting query, and the FOUND_ROWS() call fetches the total count.
Example:
SELECT SQL_CALC_FOUND_ROWS * FROM `table` WHERE `some_condition`; SELECT FOUND_ROWS();
Note: This method has a potential drawback. MySQL has a bug that impacts ORDER BY queries when using this technique, making it slower on large tables.
Caching the Count
An alternative solution involves caching the total count for a specific duration. This approach eliminates the need for a separate query to fetch the count while preserving efficiency.
Example:
Retrieve the count and cache it for 10 minutes:
SET @count = (SELECT COUNT(*) FROM `table` WHERE `some_condition`);
In subsequent queries, use the cached count:
SELECT * FROM `table` WHERE `some_condition` LIMIT 0, 10;
Caching the count significantly improves performance, especially for frequently visited pages. While it's not a single-query solution, it achieves the same result while being more efficient than double-querying.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3