简体   繁体   中英

MySQL COUNT query results in 1 always

I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 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.

Example: Using Count(*) the result's something like the following.

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

that's why COUNT exists, it always returns one row with number of selected rows

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

Count() is an aggregate function which means it returns just one row that contains the actual answer. You'd see the same type of thing if you used a function like 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.

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; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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