MySQL中count(1)、count(*) 与 count(列名) 的执行区别

执行效果:

一、count(1) and count(*)
当表的数据量大些时,对表做分析以后,使用count(1)还要比使用count()用时多了!
从执行计划来看,count(1)和count(
)的效果是同样的。可是在表作过度析以后,count(1)会比count(*)的用时少些(1w之内数据量),不过差不了多少。mysql

若是count(1)是聚索引,id,那确定是count(1)快,可是差的很小的。
由于count(),自动会优化指定到那一个字段。因此不必去count(1),用count(),sql会帮你完成优化的,所以:count(1)和count(*)基本没有差异!web

二、count(1) and count(字段)
二者的主要区别是
count(1) 会统计表中的全部的记录数,包含字段为null 的记录。
count(字段) 会统计该字段在表中出现的次数,忽略字段为null 的状况。即不统计字段为null 的记录。sql

count(*) 和 count(1)和count(列名)区别
执行效果上:svg

  1. count(*)包括了全部的列,至关于行数,在统计结果的时候,不会忽略列值为NULL。
  2. count(1)包括了忽略全部列,用1表明代码行,在统计结果的时候,不会忽略列值为NULL 。
  3. count(列名)只包括列名那一列,在统计结果的时候,会忽略列值为空(这里的空不是只空字符串或者0,而是表示null)的计数,即某个字段值为NULL时,不统计。

执行效率上:优化

  1. 列名为主键,count(列名)会比count(1)快。
  2. 列名不为主键,count(1)会比count(列名)快。
  3. 若是表多个列而且没有主键,则 count(1) 的执行效率优于 count(*)。
  4. 若是有主键,则 select count(主键)的执行效率是最优的。
  5. 若是表只有一个字段,则 select count(*)最优。

实例分析

mysql> create table counttest(name char(1), age char(2));
Query OK, 0 rows affected (0.03 sec)
 
mysql> insert into counttest values
    -> ('a', '14'),('a', '15'), ('a', '15'),
    -> ('b', NULL), ('b', '16'),
    -> ('c', '17'),
    -> ('d', null),
    ->('e', '');
Query OK, 8 rows affected (0.01 sec)
Records: 8  Duplicates: 0  Warnings: 0
 
mysql> select * from counttest;
+------+------+
| name | age  |
+------+------+
| a    | 14   |
| a    | 15   |
| a    | 15   |
| b    | NULL |
| b    | 16   |
| c    | 17   |
| d    | NULL |
| e    |      |
+------+------+
8 rows in set (0.00 sec)
mysql> select name, count(name), count(1), count(*), count(age), count(distinct(age))
    -> from counttest
    -> group by name;
+------+-------------+----------+----------+------------+----------------------+
| name | count(name) | count(1) | count(*) | count(age) | count(distinct(age)) |
+------+-------------+----------+----------+------------+----------------------+
| a    |           3 |        3 |        3 |          3 |                    2 |
| b    |           2 |        2 |        2 |          1 |                    1 |
| c    |           1 |        1 |        1 |          1 |                    1 |
| d    |           1 |        1 |        1 |          0 |                    0 |
| e    |           1 |        1 |        1 |          1 |                    1 |
+------+-------------+----------+----------+------------+----------------------+
5 rows in set (0.00 sec)