聚合操作指的是在数据查找基础上对数据的进一步整理筛选行为,实际上聚合操作也属于数据的查询筛选范围。

聚合函数

方法

功能

avg(字段名)

该字段的平均值

max(字段名)

该字段的最大值

min(字段名)

该字段的最小值

sum(字段名)

该字段所有记录的和

count(字段名)

统计该字段记录的个数

例1:找出表中的最大攻击力得到值

select avg(attack) from sanguo;

例2:表中共有多少个英雄?

select count(name) as number  from sanguo;

例3:找出表中的最大攻击力得到值

select count(*) from sanguo where attack > 200;

注:select后写聚合函数后只能写别的聚合函数,不能查找其他字段。

聚合分组

  • group by
    给查询的结果进行分组
    例1:计算每个国家的平均攻击力
select country,avg(attack) from sanguo group by country;

例2:对多个字段创建索引,此时多个字段都相同时为一组

select age,sex,count(*) from class1 group by age,sex;

例3:所有国家的男英雄中 英雄数量最多的前2名的 国家名称及英雄数量

select country count(id) as number from sanguo 
where gender="m" 
group by country 
order by number DESC 
limit 2;

使用分组时,select后面的字段为group by 分组的字段或者是聚合函数,不能包含其他内容;
group by 分组可同时依照多个字段分组,但此时多个字段值均相同才算一组;

聚合筛选

  • having
    对分组聚合后的结果进行进一步的筛选
    例1:找出平均攻击力大于105的国家的前2名,显示国家名称和平均攻击力
select country avg(attack) from sanguo
group by country 
having avg(attack) > 105 
order by avg(attack) DESC
limit 2;

注意:
having语句必须与group by 联合使用;
having弥补了where关键字不能与聚合函数联合使用的不足,where只能操作表中实际存在的字段;

去重语句

  • distinct
    不显示字段重复值
    例1:表中都有那些国家
select distinct name,country from sanguo;

例2:计算一共有多少个国家

select count(distinct country) from sanguo;

注意:
distinct和from之间所有字段都相同才会去重

聚合运算

  • 查询表记录时做数学运算
    运算符:+ - * / %
    例1:查询时显示攻击力翻倍
select name,attack*2 from sanguo;

例2:更新蜀国所有英雄攻击力 * 2

update sanguo set attack*2 where country='蜀';