SQL查询
1、总结
3、select ...聚合函数 from 表名
1、where ...
2、group by ...
4、having ...
5、order by ...
6、limit ...;
2、order by
1、给查询结果进行排序
2、... order by 字段名 ASC/DESC
3、升序:ASC(默认)
降序:DESC
4、示例
1、将英雄按防御值从高到低排序
2、将蜀国英雄按攻击值从高到低排序
3、将魏蜀两国英雄中名字为三个字的按防御值升序排列
select * from sanguo
where
country in("蜀国","魏国") and name like "___"
order by fangyu ASC;
select * from sanguo
where
(country="魏国" or country="蜀国") and name like "___"
order by fangyu;
3、limit (永远放在SQL语句的最后写)
1、作用 :限制显示查询记录的个数
2、用法
1、limit n -> 显示 n 条记录
2、limit m,n
m 表示 从第m+1条记录开始显示,显示 n 条
limit 2,3 : 第 3、4、5 三条记录
3、示例
1、在蜀国英雄中,查找防御值倒数第二名至倒数第四名的英雄的记录
select * from sanguo
where country="蜀国"
order by fangyu asc
limit 1,3;
2、在蜀国英雄中,查找攻击值前3名且名字不为 NULL 的英雄的姓名、攻击值和国家
select name,gongji,country from sanguo
where
country="蜀国" and name is not NULL
order by gongji DESC
limit 3;
4、分页
每页显示5条记录,显示第4页的内容
第1页 :limit 0,5 # 1 2 3 4 5
第2页 :limit (2-1)*5,5 # 6 7 8 9 10
第3页 :limit (3-1)*5,5 # 11 12 13 14 15
第4页 :limit (4-1)*5,5 # 16 17 18 19 20
每页显示n条记录,显示第m页 :limit (m-1)*n,n
4、聚合函数
1、分类
avg(字段名) : 求该字段平均值
sum(字段名) : 求和
max(字段名) : 最大值
min(字段名) : 最小值
count(字段名) : 统计该字段记录的个数
2、示例
1、攻击力最强值是多少
select max(gongji) from MOSHOU.sanguo;
2、统计id 、name 两个字段分别有几条记录
select count(id),count(name) from sanguo;
## 空值 NULL 不会被统计,""会被统计
3、计算蜀国英雄的总攻击力
select sum(gongji) from MOSHOU.sanguo
where country="蜀国";
4、统计蜀国英雄中攻击值大于200的英雄的数量
select count(*) from MOSHOU.sanguo
where gongji>200 and country="蜀国";
发表评论