之前一直都任务select count(1) from tab的效率要高于count(*),今天看了下执行计划才发现原来一直都是一个误解,mysql的优化器会自动转换。
直接上例子
explain SELECT count(*) FROM `employees`;
1SIMPLEemployeesindexindex_firstName44299809Using index
执行到这里我发现本机的mysql不显示wraning,我这里直接贴一个同事的测试结果
mysql> explain extended select count(*) from t1;
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | t1 | index | NULL | ind2 | 6 | NULL | 4096 | 100 | Using index |
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+-------------+
1 row in set
mysql> show warnings;
+-------+------+---------------------------------------------------------------+
| Level | Code | Message |
+-------+------+---------------------------------------------------------------+
| Note | 1003 | /* select#1 */ select count(0) AS `count(*)` from `test`.`t1` |
+-------+------+---------------------------------------------------------------+
show waring时发现select count(*) 会自动转换成count(0), 但是count某一个字段的时候就不会有这种优化了。
另外这里在贴下sql审核时什么时候要waring下
1、全表扫描
2、count(字段名) 非 count(*)
3、like
4、select *
5、oracle:用 outer join
6、查询时使用timestamp变量
总结一下,count星效率不低,mysql优化器会自动优化,另外有个waring要在自动审核时check下。