【问题标题】:What does "expr" do in MySQL's COUNT(expr) function?MySQL 的 COUNT(expr) 函数中的“expr”有什么作用?
【发布时间】:2018-11-28 19:02:03
【问题描述】:
考虑以下:
SELECT COUNT(*) FROM table;
SELECT COUNT(1) FROM table;
SELECT COUNT(-2) FROM table;
SELECT COUNT(135392) FROM table;
SELECT COUNT(field) FROM table;
SELECT COUNT(field1 + field2) FROM table;
我不清楚expr 实际做了什么,或者它可以用于什么,因为上述所有 SQL 语句都返回相同的结果。下面的例子:
+-----------+
| count(..) |
+-----------+
| 54542 |
+-----------+
MySQL 的手册 (https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html) 没有详细介绍 expr 部分,除了使用 * 符号
【问题讨论】:
标签:
mysql
sql
database
count
【解决方案1】:
COUNT(<expr>) 计算<expr> 计算结果为非NULL 值的行数。
一般来说,表达式不需要它,它只能用于单个 NULL-able 列,或者由于外部连接而可能是 NULL 的列。
【解决方案2】:
-
COUNT(*) 将统计所有行
-
如果
expr 是NOT NULL,COUNT(expr) 将计算行
如果expr 包含NULL 值,那么COUNT(expr) 可能小于COUNT(*):
SELECT COUNT(*), COUNT(1), COUNT(col)
FROM (
SELECT 'a' UNION ALL
SELECT 'b' UNION ALL
SELECT NULL
) AS t(col)
-- 3 3 2
【解决方案3】:
Expr 是表达式的缩写,它本身是“一些有效的 sql 块,在计算时会为该行产生一个值”的缩写
可以是常量、列、函数调用的结果、变量赋值、case 语句等
—equivalent
COUNT(*)
COUNT(1)
COUNT(‘a’)
—count only males. If the group is 1000 in number and 600 are female, this returns 400
COUNT(case when gender = ‘m’ then ‘a’ else null end)
作为对其他答案的补充,<expr> 可以选择以单词 DISTINCT 开头,在这种情况下,仅计算引用的实体/表达式/函数结果的唯一出现次数
—in a set of 1000 animals, returns 1000
COUNT(gender)
—in a set of 1000 animals, 600 female, returns 2 (only values M and F exist in the group)
COUNT(distinct gender)