简体   繁体   English

MySQL COUNT查询结果始终为1

[英]MySQL COUNT query results in 1 always

I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 1 . 我想知道为什么我的MySQL COUNT(*)查询总是导致->num_rows等于1

$result = $db->query("SELECT COUNT( * ) FROM u11_users");
print $result->num_rows; // prints 1

Whereas fetching "real data" from the database works fine. 从数据库中获取“真实数据”可以正常工作。

$result = $db->query("SELECT * FROM u11_users");
print $result->num_rows; // prints the correct number of elements in the table

What could be the reason for this? 这可能是什么原因?

Because Count(*) returns just one line with the number of rows. 因为Count(*)仅返回行数的一行。

Example: Using Count(*) the result's something like the following. 示例:使用Count(*) ,结果类似于以下内容。

array('COUNT(*)' => 20);
echo $result['COUNT(*)']; // 20

Reference 参考

It should return one row*. 应该返回一行*。 To get the count you need to: 要获得计数,您需要:

$result = $db->query("SELECT COUNT(*) AS C FROM u11_users");
$row = $result->fetch_assoc();
print $row["C"];

* since you are using an aggregate function and not using GROUP BY *因为您使用的是聚合函数而不是GROUP BY

that's why COUNT exists, it always returns one row with number of selected rows 这就是为什么存在COUNT的原因,它总是返回包含选定行数的一行

http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html http://dev.mysql.com/doc/refman/5.1/zh-CN/counting-rows.html

Count() is an aggregate function which means it returns just one row that contains the actual answer. Count()是一个聚合函数,这意味着它仅返回包含实际答案的一行。 You'd see the same type of thing if you used a function like max(id); 如果使用max(id)之类的函数,则会看到相同类型的事物。 if the maximum value in a column was 142, then you wouldn't expect to see 142 records but rather a single record with the value 142. Likewise, if the number of rows is 400 and you ask for the count(*), you will not get 400 rows but rather a single row with the answer: 400. 如果一列的最大值是142,那么您就不会期望看到142条记录,而只会看到一条值为142的记录。同样,如果行数是400,并且您要求count(*),那么您会发现不会得到400行,而是一行,答案是:400。

So, to get the count, you'd run your first query, and just access the value in the first (and only) row. 因此,要获得计数,您将运行第一个查询,然后仅访问第一行(也是唯一行)中的值。

By the way, you should go with this count(*) approach rather than querying for all the data and taking $result->num_rows; 顺便说一句,您应该使用count(*)方法,而不是查询所有数据并使用$result->num_rows; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need. 因为查询所有行将花费更长的时间,因为您要拉回不需要的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM