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)
最佳答案
如果列被索引,COUNT(DISTINCT id)
只需要返回列索引中的项目数。 COUNT(id)
必须将每个索引条目指向的行数相加,或者扫描所有行。
关于您的第二个问题,请参阅 count(*) and count(column_name), what's the diff? .大多数时候,COUNT(*)
是最合适的;在某些情况下,例如计算通过外部连接连接的行,您需要使用 COUNT(columnname)
因为您不想计算空行。
关于mysql COUNT(*) 与 COUNT(DISTINCT col),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34533170/