MySQL五十题-1
11.21面试50题第一题-今天也是努力学习的小杨同学
第一题的题目为:查询"01"课程比"02"课程成绩高的学生的信息及课程分数
应用的数据如下:
course表:
score表:
student表:
teacher表:
解答过程:
1.四个表格之间的联系如下
对于第一题来说我们需要的逻辑线就是
student.s_id-score.s_id-course.c_id
按照小杨的构思习惯,结果导向想要什么就select 什么 ,将题目拆分
1.查询01课程中学生的信息以及课程分数
即为:select s_id,c_id,s_score from score
2.查询02课程中学生的信息以及课程分数
即为:select s_id,c_id,s_score from score
那么下一步的思路就是将这两个表作为子查询进行联结,同时题目的要求是要查询学生的信息及课程分数
即为:select s_id,s_name,01课程分数,02课程的分数 from 建立的子查询 where 01课程分数>02课程分数;
整体的思路就是这样子,以下是具体的代码:
select s_id,s_name,a.s_score as ‘01’,b.s_score’02’ from
**第一个子查询(select s_id,c_id,s_score from score where c_id=‘’01‘’) as a
**第二个子查询为(select s_id,c_id,s_score from score where c_id=02‘’) as b
将两个子查询进行联结关键字为:inner join
(select s_id,c_id,s_score from score where c_id=‘01’)as a
INNER JOIN
(select s_id,c_id,s_score from score where c_id=‘02’)as b
on a.s_id=b.s_id
子查询建立好了之后就将我们需要的信息进行整合为:
select a.s_id,a.s_score as ‘01’,b.s_score as ‘02’ from(
(select s_id,c_id,s_score from score where c_id=‘01’)as a
INNER JOIN
(select s_id,c_id,s_score from score where c_id=‘02’)as b
on a.s_id=b.s_id
)
如图:
到这我们发现一个问题
就是这上面只有学生的id并没有学生的名字信息。
那么我们需要再在建立一个查询学生名字的子查询,那么联结的就是学生表,因为只有学生表中有学生的编码以及名字。
(select s_id,s_name from student)as s on s.s_id=b.s_id)
where a.s_score>b.s_score
同样适用inner join联结
整合为:select a.s_id,s.s_name,a.s_score as ‘01’,b.s_score as ‘02’ from(
(select s_id,c_id,s_score from score where c_id=‘01’)as a
INNER JOIN
(select s_id,c_id,s_score from score where c_id=‘02’)as b
on a.s_id=b.s_id
INNER JOIN
(select s_id,s_name from student)as s on s.s_id=b.s_id)
where a.s_score>b.s_score;
结果为:
啊这美好的一天
ps:记录自己学习的过程,别来上纲上线奥,否则小心顺着你的网线咬死你!
如果有一起学习的小伙伴可以私我呀!!一起努力!!!