在MySQL中支持的统计函数有:
在实际使用时,统计函数常与分组(group by)连用,分组是将数据按某个字段的重复值进行分类,只有当数据值有重复时才有必要进行分组。
使用统计函数的查询语法一般为:
select function(field) from table_name where condition;
select count(*) from students where gender=1;
select max(age) from students;
select sum(age) from students;
select max(age), min(age) from students;
在MySQL中分组通过group by 来实现,分组数据查询的语法形式如下:
select * from table_name where condition group by field;
如:
select gender, avg(age) from students group by gender;
如果想显示每个分组的字段,可使用group_concat()来实现,具体语法形式是:
select group_concat(field) from table_name where condition group by field;
如:
select gender,group_concat(name) from students where gender=1 group by gender;
多字段分组查询:按照group by后的字段名顺序,先按照第一个排序,再依次轮下去:
select group_concat(field) , function(field) from table_name where condition group by field1, field2, ... , fieldn;
在分组查询中,提供了having关键字来实现条件限制分组数据记录,其基本的语法形式是:
select function(field) from table_name where cindition group by field1, field2, ..., fieldn having condition;
如:
select gender, group_concat(name),avg(age) from students group by gender having avg(age)>30;