bitscn.com
1.任何情况下select count(*) from tablename是最优选择;
2.尽量减少select count(*) from tablename where col = ‘value’ 这种查询;
3.杜绝select count(col) from tablename的出现。
count(*)与count(col)
网上搜索了下,发现各种说法都有:
比如认为count(col)比count(*)快的;
认为count(*)比count(col)快的;
还有朋友很搞笑的说到这个其实是看人品的。
在不加where限制条件的情况下,count(*)与count(col)基本可以认为是等价的;
但是在有where限制条件的情况下,count(*)会比count(col)快非常多;
具体的数据参考如下:
mysql> select count(*) from cdb_posts where fid = 604;
+————+
| count(fid) |
+————+
| 79000 |
+————+
1 row in set (0.03 sec)
mysql> select count(tid) from cdb_posts where fid = 604;
+————+
| count(tid) |
+————+
| 79000 |
+————+
1 row in set (0.33 sec)
mysql> select count(pid) from cdb_posts where fid = 604;
+————+
| count(pid) |
+————+
| 79000 |
+————+
1 row in set (0.33 sec)
count(*)通常是对主键进行索引扫描,而count(col)就不一定了,另外前者是统计表中的所有符合的纪录总数,而后者是计算表中所有符合的col的纪录数。还有有区别的。
count时的where
简单说下,就是count的时候,如果没有where限制的话,mysql直接返回保存有总的行数
而在有where限制的情况下,总是需要对mysql进行全表遍历。
优化总结:
1.任何情况下select count(*) from tablename是最优选择;
2.尽量减少select count(*) from tablename where col = ‘value’ 这种查询;
3.杜绝select count(col) from tablename的出现。
bitscn.com