Mysql中的count(*)的误解

来源:互联网 发布:上海清算中心扣钱 知乎 编辑:程序博客网 时间:2024/05/21 06:01

有时候总认为count(*)会比count(1)或者count(column name)慢,其实这里面还是有个小坑的。让我们用一个例子来了解一下它们的区别:

---初始化语句create table test2 (id BIGINT PRIMARY key, name varchar(24))ENGINE=INNODB;insert into test2(id,name)values(1,null);insert into test2(id,name)values(2,'name1');insert into test2(id,name)values(3,'name2');

接下来我们分别猜测下下面的结果是多少:

select count(*) from test2 ;select count(id) from test2 ;select count(name) from test2 ;select count(name) from test2 where name is null;

当运行结果我们可以得出:3,3,2,0,为什么呢?让我来解释一下。首先count(1)指的并不是计算1的个数,而是指表的第一个字段,如果第一个字段没有建立索引,他的效率是很低的;而且count(column name)默认查询的是指定字段非空的个数,如果你想查询数据的所有行数,恰巧指定字段又是一个可存在空库数据的字段,那么得到的数据就不会是期望的值。再来说一下count(),在上述的count(column name)查询方式中,如果指定的column为限制为非空,那么mysql会将上述表达式转化为count()来进行查询。所以如果想要查询数据大小,在mysql中建议使用count(*)来执行,含义明了,速度还快。

0 0