如何计算 MySQL 查询返回的行数? [英] How can I count the numbers of rows that a MySQL query returned?
问题描述
如何计算 MySQL 查询返回的行数?
How can I count the number of rows that a MySQL query returned?
推荐答案
获取查询结果中的总行数...
您可以迭代结果并计算它们.您没有说明您使用的是什么语言或客户端库,但 API 确实提供了 mysql_num_rows 函数,它可以告诉您结果中的行数.
Getting total rows in a query result...
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
这在 PHP 中公开,例如,作为 mysqli_num_rows一>功能.当您编辑问题以提及您使用 PHP 时,这是一个使用 mysqli 函数的简单示例:
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
获取符合某些条件的行数...
只需使用 COUNT(*) - 参见 计数行 在 MySQL 手册中.例如:
Getting a count of rows matching some criteria...
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
使用 LIMIT 时获取总行数...
如果您使用了 LIMIT 子句但想知道没有它您会得到多少行,请使用 SQL_CALC_FOUND_ROWS 在您的查询中,然后是 SELECT FOUND_ROWS();
Get total rows when LIMIT is used...
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
对于非常大的表,这不会特别有效,您最好运行一个更简单的查询来获取计数并在运行查询以获取数据页之前缓存它.
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
这篇关于如何计算 MySQL 查询返回的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!