1、定义:
- count(1):常见计数方式,统计目标表的记录行数。括号里表示一个固定值,可以是任何固定的数字字符,是个常量。
- count(*):常见计数方式,统计目标表的记录行数,与count(1)执行结果相同,但是执行会根据目标表的不同进行优化。
- count(列名):常见计数方式,统计目标表某一列的非空记录数。它会统计指定列中不为NULL的行数,忽略NULL值。
-
count(distinct(列名)) :其实是 count(列名) + distinct 的结果集,指定列不为NULL,并且在字段值重复的情况下只统计一次
2、异同点
运行结果一致:count(*)和count(1)都是统计表中所有记录的行数,不论其是否包含null值。换而言之,都可以统计NULL,运行结果是一样的;count(列名)和count(distinct(列名)) 统计为该列的非空记录数,不会统计NULL
语义存在差异:count(*)和count(1)执行机制存在差异,count()函数在传入*,1,2,'abc'等值都会返回相同的结果;区别在于count(*)在传入*时,MySQL优化器会找到最小的那棵索引树进行遍历.
引入了官方文档的原话:
InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference
For
MyISAM
tables, COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is noWHERE
clause. For example:
mysql> SELECT COUNT(*) FROM student;
This optimization only applies to
MyISAM
tables, because an exact row count is stored for this storage engine and can be accessed very quickly.COUNT(1)
is only subject to the same optimization if the first column is defined asNOT NULL
.
3、总结:
对于 count(1) 和 count(*) ,效率相当,建议尽量使用 count(*),因为 MySQL 优化器会选择最小的索引树进行统计,针对此操作进行优化。
参考文献:
深度剖析:MySQL count() 函数,这下彻底明白了! - 知乎
MySQL :: MySQL 8.0 Reference Manual :: 12.19.1 Aggregate Function Descriptions