关键记忆点:
1.【关联子查询】
理解:用于每组组内比较时
应用场景:分组取每组最大值、最小值
#理解:where处的条件为两个表分别是同一组时,筛选满足2表与1表的比较条件,所以group by 可省略。
2.【limit()用法】
释义: LIMIT 5,10; // 检索记录行 6-15
LIMIT 5; //检索前 5 个记录行
一、课程练习题
--【视图】1.创建视图
#视图:可理解为需要经常用到的临时表
CREATE view 按性别汇总(性别,人数)
as
select 性别,count(*)
from student
group by 性别
--【多行子查询】2. 哪些学生的成绩比课程0002的全部成绩里的 任意一个高?
①找出课程0002的全部成绩
select 成绩
from score
where 课程号=0002
②找比①高的学生
select 学号,课程号,成绩
from score
where 成绩>any(select 成绩
from score
where 课程号='0002')
--【多行子查询】3.哪些学生的成绩比课程0002的全部成绩里的 全部一个高?
select 学号,课程号,成绩
from score
where 成绩>all(select 成绩
from score
where 课程号='0002')
--【标量子查询】4.大于平均成绩学生的学号和成绩
SELECT 学号,成绩
from score
where 成绩>(SELECT avg(成绩)
FROM SCORE )
--【关联子查询】5.查找出每个课程中大于对应课程平均成绩的数据
select 学号,课程号,成绩
from score a
where 成绩>(select avg(成绩)
from score b
where a.课程号=b.课程号)
--【关联子查询】6.找出每个课程里成绩最低的学号(分组取每组内最小值)
#错误写法:
select 学号,课程号,成绩
from score
where 成绩 in(
select min(成绩)
from score
group by 课程号)
order by 课程号;
#注:最终显示的是成绩不是按分组来的,课程2有两个成绩
#正确写法:
select 学号,课程号,成绩
from score a
where 成绩=(select min(成绩)
from score b
where a.课程号=b.课程号)
order by 课程号;
--【关联子查询】7.分组取取组内最大值
select *
from score as a
where 成绩 = (
select max(成绩)
from score as b
where b.课程号 = a.课程号);
二、sqlzoo练习题
#错误分析:代码基本逻辑都不对,框选部分是筛选条件,用在where后
#注意引号的用法
#错误分析:考察关联子查询,取每组内排序第一的值
第8题 总结
--第一次解法:
SELECT continent,name
from world w1
where name=(select w2.name
from world w2
where w1.continent=w2.continent
order by name desc
limit 1)
#desc是降序排列,答案报错
条件是按字母排序排在第一,不理解到底是升序排列还是降序排列?
--第二次解法
SELECT continent,name
FROM world x
WHERE x.name= (SELECT y.name
FROM world y
WHERE y.continent=x.continent
order by name
limit 1)
#该答案是升序排列取第一行,答案正确
--第三次解法
select continent, name
from world as x
where name <= all
(select name
from world as y
where y.continent=x.continent)
#该答案是升序排列的第一行,答案正确