Home > Database > Mysql Tutorial > How Can I Efficiently Get Total Result Count in MySQL Pagination While Using LIMIT and OFFSET?

How Can I Efficiently Get Total Result Count in MySQL Pagination While Using LIMIT and OFFSET?

Linda Hamilton
Release: 2024-11-27 11:04:12
Original
257 people have browsed it

How Can I Efficiently Get Total Result Count in MySQL Pagination While Using LIMIT and OFFSET?

Obtaining Total Results using MySQL Offset and Limit

Pagination involves retrieving subsets of data from a database based on offset and limit values. However, to determine the total number of pages, knowledge of the total number of results is required. This article presents a programming question pertaining to an efficient method for calculating this total.

Question:

In PHP/MySQL, a user implementing pagination encounters a need to determine the total number of results for a given query, even when employing offset and limit parameters. The concern is that executing a second query without the limit constraint to count rows may prove computationally wasteful. Is there a more resource-friendly approach?

Answer:

Yes, there is an optimized solution for this scenario. By utilizing the SQL_CALC_FOUND_ROWS keyword at the beginning of the initial query, MySQL will perform an automatic count of all matching rows, regardless of offset or limit restrictions. This eliminates the need for a second query.

Here's how to modify your query with SQL_CALC_FOUND_ROWS:

SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE category_id = ? LIMIT ?, ?
Copy after login

Once this modified query is executed, you can execute the following query to retrieve the total count of matching rows:

SELECT FOUND_ROWS()
Copy after login

By using SQL_CALC_FOUND_ROWS, you can efficiently retrieve both the paginated results and the total result count with a single database call.

The above is the detailed content of How Can I Efficiently Get Total Result Count in MySQL Pagination While Using LIMIT and OFFSET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template