笔者sql知识有限,欢迎大家提供更好的方法建议
相关表如下
student:
sc:
course:
1,选择‘01’课程未选02课程的姓名,学科名称,该科成绩
SELECT s.Sname,c.`
Cname`,sc.score
FROM (student s LEFT JOIN sc ON s.`S#`=sc.`S#`)
LEFT JOIN course c ON c.`C#`=sc.`C#`
WHERE sc.`S#`=(SELECT sc.`S#` FROM sc
WHERE sc.`C#`='01' AND sc.`S#` NOT IN
(SELECT sc.`S#` FROM sc WHERE sc.`C#`='02'))
解析:筛选步骤
1.在sc表中先将选02课程的学生编号筛选出来
SELECT sc.`S#` FROM sc WHERE sc.`C#`='02'
可以看到,这些结果都是已选02课程的学生编号,我们将这个结果命名为table_02
2,筛选出选择了01课程,但是s#学生编号未在table_02中
SELECT * FROM sc WHERE sc.`C#`='01' AND sc.`S#` NOT IN (SELECT sc.`S#` FROM sc WHERE sc.`C#`='02')
筛选出了,选择01课程,未选02课程的S#为06的学生
3,将3个表左连接起来,加上第二步骤中的筛选条件选出我们需要的字段
SELECT s.Sname,c.`
Cname`,sc.score
FROM (student s LEFT JOIN sc ON s.`S#`=sc.`S#`)
LEFT JOIN course c ON c.`C#`=sc.`C#`
WHERE sc.`S#`=(SELECT sc.`S#` FROM sc
WHERE sc.`C#`='01' AND sc.`S#` NOT IN
(SELECT sc.`S#` FROM sc WHERE sc.`C#`='02'))
结果为。编号为06的吴兰,选了01课程,但是未选02课程,01语文课程成绩为31,03英语课程为34