How to Determine Total Result Count in MySQL with Offset and Limit while Paginating?

Barbara Streisand
Release: 2024-10-23 12:12:01
Original
487 people have browsed it

How to Determine Total Result Count in MySQL with Offset and Limit while Paginating?

Determining Total Result Count in MySQL with Offset and Limit

Pagination is a crucial aspect of web development, allowing for efficient display of large datasets across multiple pages. When using offsets and limits in MySQL queries, it's essential to determine the total number of results to calculate the required pagination.

One approach is to run the query twice: once with the limit to retrieve the results to display, and again without the limit to count the total rows. However, this method is inefficient and can be a burden on database resources.

A more efficient solution is to utilize the SQL_CALC_FOUND_ROWS keyword. This keyword informs MySQL to calculate the total number of rows that would have been returned without the limit. The total count can then be retrieved using the FOUND_ROWS() function.

For instance, consider the following query:

SELECT * FROM table_name ORDER BY id LIMIT 10 OFFSET 20;
Copy after login

To determine the total number of rows, add SQL_CALC_FOUND_ROWS at the beginning of the query:

SELECT SQL_CALC_FOUND_ROWS * FROM table_name ORDER BY id LIMIT 10 OFFSET 20;
Copy after login

After executing this query, use FOUND_ROWS() to retrieve the total count:

$total_results = $this->db->query('SELECT FOUND_ROWS()')->row()->{'FOUND_ROWS()'};
Copy after login

This approach provides an efficient means to determine the total number of results without the need for a separate query. It saves computational resources and ensures optimal database performance, especially for large datasets.

The above is the detailed content of How to Determine Total Result Count in MySQL with Offset and Limit while Paginating?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!