2、查询同时存在” 01 “课程和” 02 “课程的情况
题目理解:
① 分两种情况 1> 数据行中没有‘01’或者‘02’课程例如06号和07号同学 2> 得分为null 但是学生学习了课程‘01’或者‘02’只是考试成绩录入有误或者同学特殊情况未参加考试;除了上面两种情况剩余的则是符合题意的同学
② 同时学习了‘01’和‘02’课程的学生(就像是大学时候的选修课01、02、03三门课程可以选择性学习,无论其成绩是否为null)
SC 表:
sid | cid | score
------------+------------+-------
01 | 01 |
01 | 02 | 90
01 | 03 | 99
02 | 01 | 70
02 | 02 | 60
02 | 03 | 80
03 | 01 | 80
03 | 02 | 80
03 | 03 | 80
04 | 01 | 50
04 | 02 | 30
04 | 03 | 20
05 | 01 | 76
05 | 02 | 87
06 | 01 | 31
06 | 03 | 34
07 | 02 | 89
07 | 03 | 98
(18 行记录)
①
解法1:夭折了……
select SC1.sid,SC1.sname,SC1.cid,SC.cid,SC.score
from ( student cross join course) AS SC1 left join SC
ON SC1.sid=SC.sid
where SC1.cid=SC.cid
order by SC1.sid,SC1.cid;
以上部分程序的运行结果和博主想象的不太一样:我以为连接健可以是两列或者变相的用两列作为连接健实现外联结,但实际上好像行不通(有大神明白我的意思,指点下吗)
用非唯一约束列作为连接健理论上应该是在连接的基础上再加一个交叉连接
解法2:
SELECT C1.sid, C3.sname, C3.sage, C3.ssex, C1.score AS score1,
C2.score AS score2
FROM (SELECT * FROM SC WHERE Cid = '01') AS C1
INNER JOIN (SELECT * FROM SC WHERE Cid = '02') AS C2
ON C1.sid = C2.sid
INNER JOIN Student AS C3
ON C1.sid = C3.sid
WHERE C1.score <> C2.score OR C1.score = C2.score;
②
解法1:
select s.sid ,s.sname,SC.cid,SC.score
from student AS S inner join SC
on S.sid=SC.sid
where '01' in ( select cid
from SC
where S.sid=sc.sid
)
and '02' IN ( select cid
from SC
where S.sid=sc.sid
);
如果where字句的两个条件能合并就会简洁很多,可惜暂时不知道方法,也没查到(有没有大神知道方法的,求指点!我好想从哪里看到过postgresql可以用数组?),等以后看到再回来补充吧,而且这种方法貌似有点“循环”的意思?!
解法2:
SELECT C1.sid, C3.sname, C3.sage, C3.ssex, C1.score AS score1,
C2.score AS score2
FROM (SELECT * FROM SC WHERE Cid = '01') AS C1
INNER JOIN (SELECT * FROM SC WHERE Cid = '02') AS C2
ON C1.sid = C2.sid
INNER JOIN Student AS C3
ON C1.sid = C3.sid ;
①和②的第二种解法都是网上的答案(②中第二种方法是根据原答案做了稍许更改,null值无法用< > =比较大小)