以前一直都任務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星效率不低,mysql優化器會自動優化,另外有個waring要在自動審覈時check下。shell