【发布时间】:2016-04-04 15:26:15
【问题描述】:
Q1:为什么 count(*) 比 count(distinct col) 慢很多?
Q2:id 应该总是使用 count(distinct col) 吗?
select count(id) from source;
+-----------+
| count(id) |
+-----------+
| 22713 |
+-----------+
1 row in set (0.73 sec)
mysql> select count(distinct id) from source;
+--------------------+
| count(distinct id) |
+--------------------+
| 22836 |
+--------------------+
1 row in set (0.08 sec)
【问题讨论】:
-
你的架构是什么样的?您是否使用 explain 运行查询?
-
要确定我们需要查看表结构、索引和解释计划。 Count distinct id 准确返回字段的不同计数。 count(id) 将返回重复项的计数(如果存在)。您的结果的奇怪之处在于,如果没有发生数据更改,则不同计数大于我永远不会期望的计数。如果 ID 已编入索引,引擎会简单地计算 idx 中的唯一值,如果它已编入索引并且有重复项,则可能必须执行全表扫描。不,你不应该总是使用一个,在你的结果中使用你需要的东西
-
在我看来,您的结果与使用的 SQL 配对不正确。如果它们正确配对,我无法理解为什么 count(ID) 在同一个数据源上会 > count (Distinct ID)。 (除非表统计信息或索引损坏)
标签: mysql