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)