时间:2021-07-01 10:21:17 帮助过:5人阅读
执行效率上:
列名为主键,count(列名)会比count(1)快
列名不为主键,count(1)会比count(列名)快
如果表多个列并且没有主键,则 count(1) 的执行效率优于 count(*)
如果有主键,则 select count(主键)的执行效率是最优的
如果表只有一个字段,则 select count(*)最优。
转自:http://eeeewwwqq.iteye.com/blog/1972576
实例分析
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)
额外参考资料:http://blog.csdn.net/lihuarongaini/article/details/68485838
SQL中 count(*)和count(1)的对比,区别
标签:sdn net 多少 name com set rom sel group