第一弹:
以下为表关系:
#1.查询选修“数据结构”这门课程的学生姓名
这里的表对应关系very复杂,所以我一开始选择使用嵌套语句
select studentName
from Student
where studentNo in
(select studentNo
from Score
where courseNo in
(select courseNo
from Course
where CourseName='数据结构'));
这样有些弯弯绕绕,不如直接用连接语句。
select studentName
from Student,Score,Course
where Student.studentNo=Score.studentNo
and Score.courseNo=Course.courseNo
and courseName='数据结构';
#2.查询选修了课程编号为001和002的学生姓名、分数和课程号。
这里踩了坑,没看见Score表里就有courseNo,在Course表里苦苦挣扎,发现跑的太远了- -|
还有就是001和002不能连等,or之后要重写“什么=什么”;(还有这个分号,是english的)
select studentName,score,courseNo
From Student,Score
where Student.studentNo=Score.studentNo
and Score.courseNo='001'or Score.courseNo='002';
#3.查询学过课程号为 001 但是没有学过课程号为 002 的课程的学生学号、 课程号和分数。
这里变化的只有“没学过002课程”的这个条件,这里我一开始选用在连接表查询下运用比较运算符<>不等于,查询出结果。如果在不连接初始表的情况下,关于两个表最终信息的查询我能做到的最简单代码如下。
select studentName,score,courseNo
From Student,Score
where Student.studentNo=Score.studentNo
and Score.courseNo='001'
and Score.courseNo<>'002';
#4. 查询至少有一门课与学号为’1500001’的学生所学相同的学生的学号和姓名。
考察的应该是any,这里除去了1500001的情况。
select studentNo,studentName
from Student
where studentNo<>'1500001'and studentNo in
( select studentNo from Score where courseNo=any
(select courseNo from Score where studentNo='1500001')
);
稍微改成连接两个需要的表,这样可以少写一个嵌套语句。BUT我在用join连接表时,系统在studentNo处反复报错,说studenNo不明确,应该是在join后的表中studentNo出现多次以至于无法定位。
select distinct studentNo,studentName
From Score inner join Student on Student.studentNo=Score.studentNo
where Score.studentNo <>'1500001' and courseNo =any
(select courseNo from Score where Score.studentNo='1500001');
#5.查询至少选修了学号为“0700001”学生所选修的所有课程的学生姓名。
这里把any改成all即可。
select studentNo,studentName
from Student
where studentNo<>'0700001'and studentNo in
( select studentNo from Score where courseNo =all
(select courseNo from Score where studentNo='1500001')
);
select *
from Student
where month(birthday)=11;
select *
from Student
where studentNo not in
(select studentNo from Score);
关于IN的方法,我觉得其实就是这样的,意义一样,即把空值找出来。
select *
from Student
left join Score on Student.studentNo=Score.studentNo
where score is null;
#8. 查询选修过课程的学生姓名。
select studentName
from Student
where studentNo in
(select studentNo from Score,Course where Score.courseNo=Course.courseNo);
TO BE CONTINUED——