Counting the number of rows returned by a MySQL query is crucial for various database operations. This article provides comprehensive solutions for this task, catering to different scenarios and techniques.
The simplest method to obtain the total number of rows is to iterate through the result and increment a counter. However, MySQL offers a built-in function, mysql_num_rows, which provides a direct count of the rows. For example, in PHP, you can use mysqli_num_rows as follows:
<code class="php"><?php $result = mysqli_query($link, "SELECT * FROM table1"); $num_rows = mysqli_num_rows($result); echo "$num_rows Rows\n"; ?></code>
To count rows that meet specific criteria, use the COUNT(*) function. For instance, to count rows where bar is equal to 'value':
SELECT COUNT(*) FROM foo WHERE bar= 'value';
If you use the LIMIT clause but want to know the total number of rows without applying the limit, use SQL_CALC_FOUND_ROWS followed by SELECT FOUND_ROWS(). For example:
<code class="sql">SELECT SQL_CALC_FOUND_ROWS * FROM foo WHERE bar="value" LIMIT 10; SELECT FOUND_ROWS();</code>
However, note that SQL_CALC_FOUND_ROWS is deprecated as of MySQL 8.0.17 and will be removed in later versions. It is recommended to use a separate query to calculate the count.
For large tables, running a separate query for counting can be inefficient. Instead, consider caching the count by executing a simpler query once and reusing it before launching more complex queries.
The above is the detailed content of How to Efficiently Count Rows in Your MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!