更新时间:2022-06-06 08:59:08
基本上, count(1)
产生的结果与 count(*)
相同:,它计算由 group by
子句定义的组中的记录数.
Basically, count(1)
produces just the same result as count(*)
: that is, it counts the number of records in the group defined by the group by
clause.
为什么? count(< expr>)
对< expr>
的每个非 null
值进行计数.这里给它一个常量值 1
,它永远不会为 null
-因此它计算所有行.
Why? count(<expr>)
counts every non-null
value of <expr>
. Here it is given a constant value, 1
, that is never null
- so it counts all rows.
我不推荐 count(1)
;检查每一行是否为空需要仅计算所有行的数据库工作.一些数据库可能会将 count(1)
优化为 count(*)
(显然,此固定表达式永远不会为 null
),但是当您可以优化自己的时候又何必呢?只需始终使用 count(*)
.
I wouldn't recommend count(1)
; checking for nullity of each and every row requires more work for the database that just counting all rows. Some databases might optimize count(1)
as count(*)
under the hood (as it is obvious that this fixed expression will never be null
), but why bother, when you can optimize yourself already? Just use count(*)
consistently.