count()是聚合函數,對於返回的結果集,一行行地判斷,累計值加1,最後返回累計值,count(*)、count(主鍵ID)和count(1)表示返回知足條件的結果集的總行數。mysql
count()聚合函數統計非NULL與NULL值的區別:sql
一、count(字段)不統計NULL記錄,即表示知足條件的數據行裏參數字段不爲NULL的行函數
二、count(1)和count(*)會記錄NULL值性能
CREATE TABLE `t1` ( `c1` varchar(30) NOT NULL, `c2` varchar(20) NOT NULL, `c3` varchar(40) NOT NULL, `c4` varchar(10) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='ceshi_count'
mysql> explain select count(*) from t1; +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | 1 | SIMPLE | t1 | ALL | NULL | NULL | NULL | NULL | 1 | NULL | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ 1 row in set (0.01 sec)
mysql> alter table t1 add primary key (c1); Query OK, 0 rows affected (0.16 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select count(*) from t1; +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ | 1 | SIMPLE | t1 | index | NULL | PRIMARY | 92 | NULL | 1 | Using index | +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ 1 row in set (0.00 sec)
mysql> alter table t1 add index idx_c3(c3); Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select count(*) from t1; +----+-------------+-------+-------+---------------+--------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+--------+---------+------+------+-------------+ | 1 | SIMPLE | t1 | index | NULL | idx_c3 | 122 | NULL | 1 | Using index | +----+-------------+-------+-------+---------------+--------+---------+------+------+-------------+ 1 row in set (0.00 sec)
四、表有多個二級索引,則使用key_len小的二級索引進行掃描優化
mysql> alter table t1 add index idx_t1_c4(c4); Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select count(*) from t1; +----+-------------+-------+-------+---------------+-----------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+-----------+---------+------+------+-------------+ | 1 | SIMPLE | t1 | index | NULL | idx_t1_c4 | 33 | NULL | 1 | Using index | +----+-------------+-------+-------+---------------+-----------+---------+------+------+-------------+ 1 row in set (0.00 sec)