Home > Database > Mysql Tutorial > How to Count Rows Beyond LIMIT in MySQL Queries?

How to Count Rows Beyond LIMIT in MySQL Queries?

Susan Sarandon
Release: 2024-11-12 09:43:01
Original
424 people have browsed it

How to Count Rows Beyond LIMIT in MySQL Queries?

Counting Rows Beyond LIMIT in MySQL Queries

Problem:

When executing a MySQL query with a LIMIT clause, it can be challenging to obtain the total number of rows in the table that satisfy the query conditions. This is particularly true when using complex JOIN statements and WHERE clauses.

Solution:

To address this issue, MySQL provides the SQL_CALC_FOUND_ROWS keyword. When this keyword is used, it instructs MySQL to calculate the total number of rows that would have been retrieved without the LIMIT clause.

Example:

Consider the following MySQL query:

SELECT A.ID, A.NAME, B.ID, B.NAME
FROM table1 A
JOIN table2 B ON ( A.ID = B.TABLE1_ID )
WHERE
    cond1, cond2, ..., condN
LIMIT 10
Copy after login

To obtain the total number of rows without the LIMIT clause, execute the following two statements in the same order:

SELECT SQL_CALC_FOUND_ROWS A.ID, A.NAME, B.ID, B.NAME
FROM table1 A
JOIN table2 B ON ( A.ID = B.TABLE1_ID )
WHERE
  cond1, cond2, ..., condN
LIMIT 10

SELECT FOUND_ROWS();
Copy after login

The first statement calculates the total rows satisfying the query conditions, while the second statement retrieves the total count from the FOUND_ROWS() function.

The above is the detailed content of How to Count Rows Beyond LIMIT in MySQL Queries?. 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