# 将英雄按防御值从高到低排序
select * from sanguo order by fangyu desc;
# 将蜀国英雄按攻击值从高到低排序
select * from sanguo where country = "蜀国" order by gongji desc;
# 将魏蜀两国英雄中名字为三个字的按防御值升序排列
select * from sanguo where
country in("魏国","蜀国") and
name like "___" order by fangyu asc;
limit
显示查询记录的条数
永远放在SQL语句的最后面
limit n 显示n条记录
limit m,n m从0开始计数,表示从第m+1条记录开始显示,n代表显示几条
分页, 每页显示n条记录,显示第m页:limit (m-1)*n,n
# 在蜀国英雄中,查找防御值倒数第二名至倒数第四名的英雄的记录
select * from sanguo where country = "蜀国" order by fangyu asc limit 1,3;
# 在蜀国英雄中,查找攻击值前3名且名字不为 NULL 的英雄的姓名、攻击值和国家
select * from sanguo where country = "蜀国" and
name is not null order by gongji desc limit 3;
# 查询表中一共有几个国家
select country from sanguo group by country;
# 计算每个国家的平均攻击力
select country,avg(gongji) from sanguo group by country;
# 查找所有国家中英雄数量最多的前2名的国家名称和英雄数量
# 先分组,再聚,再排序
select country,count(id) as number from sanguo
group by country order by number desc limit 2;
# 找出平均攻击力>105的国家的前2名,显示国家名和平均攻击力
select country,avg(gongji) as avggj from sanguo
group by country having avggj > 105 order by avggj desc limit 2;
distinct
不显示字段的重复值
distinct处理的是distinct和from之间的所有字段,所有字段值必须全部相同才能去重
distinct不能对任何字段做聚合处理
# 表中都有哪些国家
select distinct country from sanguo;
# 计算蜀国一共有多少个英雄
select count(distinct id) from sanguo where country = "蜀国";
查询表记录时做数学运算
# 查询时所有英雄攻击力翻倍
select id,name,gongji*2 from sanguo;
聚合函数
avg(字段名): 求该字段平均值
sum(字段名): 求和
max(字段名): 最大值
min(字段名): 最小值
count(字段名): 统计该字段记录的个数
# 攻击力最强值是多少
select max(gongji) from sanguo;
# 统计id,name 两个字段分别有几条记录
select count(id),count(name) from sanguo;
# 计算蜀国英雄的总攻击力
select sum(gongji) from sanguo where country = "蜀国";
# 统计蜀国英雄中攻击值大于200的英雄的数量
select count(*) from sanguo where country = "蜀国" and gongji > 200;