前言
最近看到一篇关于COUNT查询效率的博客,主要就是探究COUNT(*)、COUNT(1)、COUNT(主键)、COUNT(字段)之间哪个查询效率更高一些。 刚好手里有一个1200W测试数据的表,本着好奇的心态,我们也试一试不同COUNT方式之间有多大的差异。 注意:以下测试均在MySQL8.0.27下的InnoDB中进行,且在本机进行查询测试,避免网络延迟对查询快慢造成影响。
测试
COUNT(*)
 三次查询结果分别是:6.99s、6.96s、6.97s。
COUNT(1)
 三次查询结果分别是:6.95s、6.97s、6.97s。
COUNT(主键)
 三次查询结果分别是:6.95s、6.96s、6.99s。
COUNT(有索引且非NULL字段)
 三次查询结果分别是:6.97s、7.00s、6.96s。
COUNT(无索引且非NULL字段)
 三次查询结果分别是:6.97s、6.98s、6.97s。
结果分析
单看查询时长,这几种COUNT方式之间并没有拉开差距,所以我们结合EXPLAIN语句,分析一下原因。 各SQL语句的执行计划结果如下:      COUNT(mobile)使用mobile字段索引,COUNT(name)全表扫描,这都可以理解。 没想到的是,COUNT(*)、COUNT(1)、COUNT(id)这三个查询都是用的mobile字段的索引。 即使我使用“FORCE INDEX(PRIMARY)”来强制使用主键索引,也没能改变最终的查询时长。 注意:这里没有尝试COUNT(可为NULL字段)的查询例子,因为COUNT(字段)只会记录非NULL的数据量,会影响我们的对比测试结果。
不严谨的结论
关于COUNT(*)和COUNT(1)的区别, MySQL官方文档已经给出了解释。没有区别。
InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.
关于COUNT(字段)和COUNT(*)的区别,就是COUNT(*)返回检索到的行数的计数,无论是否包含 NULL 值。而COUNT(字段)返回目标字段中,非NULL值的计数。 至于数据扫描逻辑,这里引用官方的解释:
InnoDB processes SELECT COUNT(*) statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. If a secondary index is not present, InnoDB processes SELECT COUNT(*) statements by scanning the clustered index. InnoDB 通过遍历最小的可用二级索引来处理 SELECT COUNT(*) 语句,除非索引或优化器提示指示优化器使用不同的索引。如果二级索引不存在,InnoDB 通过扫描聚集索引来处理 SELECT COUNT(*) 语句。
最后,COUNT(*)、COUNT(1)、COUNT(字段)看起来没有本质的区别……
参考文档: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_count
|