count函数是用来统计表中或数组中记录的一个函数,下面我来介绍在mysql中count函数用法与性能比较吧。count(*) 它返回检索行的数
count函数是用来统计表中或数组中记录的一个函数,下面我来介绍在mysql中count函数用法与性能比较吧。count(*) 它返回检索行的数目, 不论其是否包含 null值。
select 从一个表中检索,,而不检索其它的列,并且没有 where子句时, count(*)被优化到最快的返回速度。
例如:select count(*) from student;
count(distinct 字段),返回不同的非null值数目;若找不到匹配的项,则count(distinct)返回 0 。
这个优化仅适用于 myisam表, 原因是这些表类型会储存一个函数返回记录的精确数量,而且非常容易访问。
对于事务型的存储引擎(innodb, bdb), 存储一个精确行数的问题比较多,原因是可能会发生多重事物处理,而每个都可能会对行数产生影响。
例, 创建用于测试的数据表,以进行count数据统计:
create table `user` (
`id` int(5) unsigned not null auto_increment,
`name` varchar(10) default null,
`password` varchar(10) default null,
primary key (`id`)
) engine=myisam auto_increment=4 default charset=latin1
测试数据为:
1 name1 123456
2 name2 123456
3 name3 123456
4 name4 null
请注意以下查询的返回结果:
1,select count(*) from `user`
2,select count(name) from `user`
3,select count(password) from `user`
输出结果:4,4,3
原因分析:
1,count(*)是对行数目进行计数,所以结果为4。
2,count(column_name)是对列中不为空的行进行计数,所以count(name)=4,而count(password)=3。
以上二点,在使用count函数时,要注意下。
使用group by对每个owner的所有记录分组,没有它,你会得到错误消息:
mysql> select owner, count(*) from pet;
error 1140 (42000): mixing of group columns (min(),max(),count(),...)
with no group columns is illegal if there is no group by clause
count( )和group by以各种方式分类你的数据。下列例子显示出进行动物普查操作的不同方式。
每种动物的数量:
mysql> select species, count(*) from pet group by species;
+---------+----------+
| species | count(*) |
+---------+----------+
| bird | 2 |
| cat | 2 |
| dog | 3 |
| hamster | 1 |
| snake | 1 |
+---------+----------+
每种性别的动物数量:
mysql> select sex, count(*) from pet group by sex;
+------+----------+
| sex | count(*) |
+------+----------+
| null | 1 |
| f | 4 |
| m | 4 |
+------+----------+
(在这个输 出中,null表示“未知性别”。)
按种类和性别组合的动物数量:
mysql> select species, sex, count(*) from pet group by species, sex;
+---------+------+----------+
| species | sex | count(*) |
+---------+------+----------+
| bird | null | 1 |
| bird | f | 1 |
| cat | f | 1 |
| cat | m | 1 |
| dog | f | 1 |
| dog | m | 2 |
| hamster | f | 1 |
| snake | m | 1 |
+---------+------+----------+
若 使用count( ),你不必检索整个表。例如, 前面的查询,当只对狗和猫进行时,应为:
mysql> select species, sex, count(*) from pet
-> where species = 'dog' or species = 'cat'
-> group by species, sex;
+---------+------+----------+
| species | sex | count(*) |
+---------+------+----------+
| cat | f | 1 |
| cat | m | 1 |
| dog | f | 1 |
| dog | m | 2 |
+---------+------+----------+
或, 如果你仅需要知道已知性别的按性别的动物数目:
mysql> select species, sex, count(*) from pet
-> where sex is not null
-> group by species, sex;
+---------+------+----------+
| species | sex | count(*) |
+---------+------+----------+
| bird | f | 1 |
| cat | f | 1 |
| cat | m | 1 |
| dog | f | 1 |
| dog | m | 2 |
| hamster | f | 1 |
| snake | m | 1 |
+---------+------+----------+
顺便提下mysql的distinct的关键字有很多你想不到的用处
1.在count 不重复的记录的时候能用到
比如select count( distinct id ) from tablename;
就是计算talbebname表中id不同的记录有多少条
2,在需要返回记录不同的id的具体值的时候可以用
比如select distinct id from tablename;
返回talbebname表中不同的id的具体的值