[英]count(*) and count(column_name), what's the diff?
count(*)
和count(column_name)
,mysql的区别是什么。
COUNT(*)
counts all rows in the result set (or group if using GROUP BY). COUNT(*)
计算结果集中的所有行(如果使用GROUP BY,则计算组)。 COUNT(column_name)
only counts those rows where column_name
is NOT NULL. COUNT(column_name)
仅计算column_name
为NOT NULL的行。 This may be slower in some situations even if there are no NULL values because the value has to be checked (unless the column is not nullable). COUNT(1)
is the same as COUNT(*)
since 1 can never be NULL. COUNT(1)
与COUNT(*)
相同,因为1永远不能为NULL。 To see the difference in the results you can try this little experiment: 要查看结果的差异,您可以尝试这个小实验:
CREATE TABLE table1 (x INT NULL);
INSERT INTO table1 (x) VALUES (1), (2), (NULL);
SELECT
COUNT(*) AS a,
COUNT(x) AS b,
COUNT(1) AS c
FROM table1;
Result: 结果:
a b c 3 2 3
根据列定义 - 如果您的列允许NULL - 您可能会得到不同的结果(在Mark已经告知的某些情况下,它可能会慢于count(列))。
There is no performance difference between COUNT (*)
, COUNT (ColumnName)
, COUNT (1)
. COUNT (*)
, COUNT (ColumnName)
, COUNT (1)
之间没有性能差异。
Now, if you have COUNT (ColumnName)
then the database has to check if the column has a NULL
value, and NULL
s are eliminated from aggregates. 现在,如果您有
COUNT (ColumnName)
那么数据库必须检查列是否具有NULL
值,并且从聚合中消除NULL
。 So COuNT (*)
or COUNT (1)
is preferable to COUNT (ColumnName)
unless you want COUNT (DISTINCT ColumnName)
所以
COuNT (*)
或COUNT (1)
最好COUNT (ColumnName)
,除非你想COUNT (DISTINCT ColumnName)
In most cases there's little difference, and COUNT(*)
or COUNT(1)
is generally preferred. 在大多数情况下,差异很小,通常首选
COUNT(*)
或COUNT(1)
。 However, there's one important situation where you must use COUNT(columnname)
: outer joins. 但是,有一个重要的情况是必须使用
COUNT(columnname)
:outer join。
If you're performing an outer join from a parent table to a child table, and you want to get zero counts in rows that have no related items in the child table, you have to use COUNT(column in child table)
. 如果您正在从父表执行外连接到子表,并且您希望在子表中没有相关项的行中获得零计数,则必须使用
COUNT(column in child table)
。 When there's no matches, that column will be NULL
, and you'll get the desired zero count (actually, you'll get NULL
, but you can convert that to 0
with IFNULL()
or COALESCE()
). 当没有匹配时,该列将为
NULL
,并且您将获得所需的零计数(实际上,您将获得NULL
,但您可以使用IFNULL()
或COALESCE()
将其转换为0
)。 If you use COUNT(*)
, it counts the row from the parent table, so you'll get a count of 1
. 如果你使用
COUNT(*)
它计算从父表中的行,所以你会得到的计数1
。
SELECT c.name, COALESCE(COUNT(o.id), 0) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.