MySQL基础之 统计函数总结
五种统计函数:count()、max()、avg()、min()、max()函数
count()函数
count()函数在进行计算的时候,是分情况进行计算的,主要是一下两种
1、采用count(*)对表中的记录进行统计,不管表字段中包含的是NULL值还是非NULL值,都会参与计算
2、而采用count(field)方式对表中的记录进行统计,如果所在的field中包含有NULL值,将忽略NULL值。
举例所示:
mysql> select * from test1_1; #可以看出来表中一共有6条记录,其中有条记录的name列包含NULL值 +----+--------+ | id | name | +----+--------+ | 1 | 超峰 | | 2 | b | | 3 | c | | 4 | a | | 5 | chen | | 6 | NULL | +----+--------+ 6 rows in set (0.00 sec) mysql> select count(*) from test1_1; +----------+ | count(*) | +----------+ | 6 | +----------+ 1 row in set (0.00 sec) mysql> select count(name) from test1_1; #NULL值将不参与计算 +-------------+ | count(name) | +-------------+ | 5 | +-------------+ 1 row in set (0.00 sec)
sum()函数
sum()函数实现统计指定字段值之和,在具体统计时将忽略NULL值,但是不会忽略0值
举例子:
mysql> select * from test1_1; +----+--------+-------+ | id | name | grade | +----+--------+-------+ | 1 | 超峰 | 99 | | 2 | b | 90 | | 3 | c | 95 | | 4 | a | 85 | | 5 | chen | 90 | | 6 | NULL | 90 | +----+--------+-------+ 6 rows in set (0.00 sec) mysql> select sum(grade) from test1_1; +------------+ | sum(grade) | +------------+ | 549 | +------------+ 1 row in set (0.00 sec) mysql> update test1_1 set grade=NULL where id=6; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test1_1; +----+--------+-------+ | id | name | grade | +----+--------+-------+ | 1 | 超峰 | 99 | | 2 | b | 90 | | 3 | c | 95 | | 4 | a | 85 | | 5 | chen | 90 | | 6 | NULL | NULL | +----+--------+-------+ 6 rows in set (0.00 sec) mysql> select sum(grade) from test1_1; #会发现NULL值没有参与计算 +------------+ | sum(grade) | +------------+ | 459 | +------------+ 1 row in set (0.00 sec)
MAX()和MIN()函数
MAX函数和MIN函数会忽略值为NULL的数据,但是不会忽略值为0的数据
在此不做举例
针对没有任何数据的表,这五种函数的返回值是什么呢?
举例子:
mysql> select * from test1_5; Empty set (0.00 sec) mysql> select count(*),avg(id),sum(id),max(id),min(id) from test1_5; +----------+---------+---------+---------+---------+ | count(*) | avg(id) | sum(id) | max(id) | min(id) | +----------+---------+---------+---------+---------+ | 0 | NULL | NULL | NULL | NULL | +----------+---------+---------+---------+---------+ 1 row in set (0.00 sec)
看的出来只有count函数的返回值是0,其他的函数返回值都是NULL。