简体   繁体   English

COUNT(*)返回错误的数字

[英]COUNT(*) return wrong number

It seems I don't get it something. 看来我什么都不懂。 Please consider this query 请考虑此查询

SELECT COUNT(*) AS `numrows` 
FROM (`exp_channel_titles` ch) 
JOIN `exp_channel_data` cd ON `cd`.`entry_id`=`ch`.`entry_id` 
LEFT JOIN `exp_matrix_data` md ON `md`.`entry_id`=`ch`.`entry_id` and field_id = 14 
LEFT JOIN `exp_assessment_users` au ON `au`.`entry_id`=`ch`.`entry_id` 
WHERE ch.channel_id = 4 GROUP BY `ch`.`entry_id`

it returns 2 它返回2

but if I change it to 但是如果我将其更改为

SELECT * 
FROM (`exp_channel_titles` ch) 
JOIN `exp_channel_data` cd ON `cd`.`entry_id`=`ch`.`entry_id` 
LEFT JOIN `exp_matrix_data` md ON `md`.`entry_id`=`ch`.`entry_id` and field_id = 14 
LEFT JOIN `exp_assessment_users` au ON `au`.`entry_id`=`ch`.`entry_id` 
WHERE ch.channel_id = 4 GROUP BY `ch`.`entry_id`

result is 1 row only. 结果仅为1行。 How so? 怎么会这样?

You're grouping, which means internally matching rows are collapsed into a single entity. 您正在分组,这意味着内部匹配的行将折叠为一个实体。 eg consider a fake table like this: 例如,考虑这样的假表:

field
-----
a
a

Yes, a one field table, with two records, both of which have the value a in them. 是的,一个字段表具有两个记录,两个记录中的值均为a

SELECT *
FROM table
GROUP BY field

group by will find all fields which have the same value, and collapse them down into a SINGLE record, so your two records of a become one row in the result set, and you end up with group by将查找具有相同值的所有字段,并将它们折叠为SINGLE记录,因此您的a的两条记录在结果集中成为一行,最后得到

field
-----
a

But doing 但是做

SELECT count(*)
FROM table
GROUP BY field

changes things. 改变了一切。 Now the DB will literally count how many records were collapsed down into the single row of result set. 现在,数据库将从字面上计算将多少记录折叠到结果集的单行中。 So you still get a SINGLE row in the result set, which contains a count of how many rows were collapsed by the group by : 因此,您仍会在结果集中得到一个单行,其中包含一个按group by折叠的行数的计数依据:

count(*)
--------
2

One row, with a value of 2, because there were two rows with a . 一行,为2的值,因为有两排, a

Now if you had a table with more records: 现在,如果您有一个包含更多记录的表:

field
-----
a
a
b
c
c
c

You would get: 您将获得:

SELECT * ... GROUP BY field

field
-----
a
b
c

SELECT count(*), field ... GROUP BY field

count(*)   field
----------------
2          a
1          b
3          c

again, 3 rows of results, but note how the count represents how many of each grouped field there are in the original table. 同样,返回3行结果,但请注意计数是如何表示原始表中每个分组字段的数量。

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

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