杂文(3):数据库查找数据类题目练习

更新于2021年1月18日17:07:10
题目来自于这个大佬的博客:超经典SQL练习题,做完这些你的SQL就过关了
同时这个大佬有解析,说的很清楚:呕心吐血之作-Mysql经典练习题的答案以及解析 代码是参考的这位知乎大佬的,把#都改成id了。我就是写个自己的思路,加强学习。(脑瘫瘫学习法)

1.查询" 01 “课程比” 02 "课程成绩高的学生的信息课程分数
首先查出01和02课程都考了的学生的课程分数

select a.*, b.* from 
(select * from sc where Cid = '01') a
left join (select * from sc where Cid = '02') b
on a.Sid = b.Sid

在此基础上再left join student表的信息,即学生的信息,再用where子句比较谁高

select a.*, b.*, c.* from 
(select * from sc where Cid = '01') a
left join (select * from sc where Cid = '02') b
on a.Sid = b.Sid
left join student c
on a.Sid = c.Sid
where a.score > b.score;

2.查询存在" 01 “课程但可能不存在” 02 "课程的情况(不存在时显示为 null )

select a.*, b.* from
(select * from sc where Cid = '01') a
left join
(select * from sc where Cid = '02') b
on a.Sid = b.Sid;

可能是01和02课程都要看到吧,其实select * from sc where Cid = '01’就行了。
3. 查询学过「张三」老师授课的同学的信息。
第一步:查出张三老师的tid;第二步:该tid对应的课程的cid;第三步:该cid对应的学生的sid;第四步:这若干个sid对应的学生信息。

select * from student where sid in
(select sid from sc where cid in //或者=
(select Cid from course where Tid in //或者=
(select tid from teacher where tname ='张三')));

中间第二第三步用in或者=都可以,但是第四步用=会报错返回 Subquery returns more than 1 row。 因为这里查询条件是若干个sid。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44445507/article/details/112787941
今日推荐