mysql中select的count星和count1有区别么

以前一直都任务select count(1) from tab的效率要高于count(*),今天看了下执行计划才发现原来一直都是一个误解,mysql的优化器会自动转换。mysql

直接上例子web

explain SELECT count(*) FROM `employees`;

1	SIMPLE	employees	index		index_firstName	44		299809	Using 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下sql

一、全表扫描
二、count(字段名) 非 count(*)
三、like
四、select *
五、oracle:用 outer join
六、查询时使用timestamp变量

总结一下,count星效率不低,mysql优化器会自动优化,另外有个waring要在自动审核时check下。shell

相关文章
相关标签/搜索