线上的一个大表(ENGINE=InnoDB) 接近5000万条记录 比较count(*)与count(id)的查询时间 发现count(*)要明显优于count(id) 如下所示
不带where条件
select count(id) from op_log;
+-----------+
| count(id) |
+-----------+
| 49011955 |
+-----------+
1 row in set (12.46 sec)
select count(*) from op_log;
+----------+
| count(*) |
+----------+
| 49011982 |
+----------+
1 row in set (10.28 sec)
并且这一结果是可重复的
带where条件的情况下的两者比较
select count(id) from op_log where is_availability=1;
+-----------+
| count(id) |
+-----------+
| 49012832 |
+-----------+
1 row in set (17.29 sec)
select count(*) from op_log where is_availability=1;
+----------+
| count(*) |
+----------+
| 49012901 |
+----------+
1 row in set (16.57 sec)
仍然count(*)快于count(id) is_availability是一个索引: KEY is_availability (is_availability,is_del)
想知道为什么count(*)要优于count(id) 两者有什么区别?官方文档也没提到原因。
使用的数据库版本 5.6.21-1~dotdeb.1-log
其他补充信息
SHOW VARIABLES LIKE 'storage_engine';
+----------------+--------+
| Variable_name | Value |
+----------------+--------+
| storage_engine | InnoDB |
+----------------+--------+
show create table op_log\G
) ENGINE=InnoDB AUTO_INCREMENT=49037362 DEFAULT CHARSET=utf8
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
说明存储引擎先
简单来说 count(*) 只有在MyISAM引擎下才优于 count(id). 因为MyISAM本身存储了row count.