时间:2021-07-01 10:21:17 帮助过:33人阅读
假设有一张成绩表(score):字段如下: sid:学生学号, cid:课程编号, score:成绩 求所修课程完全相同的同学的学号。这个问题其实关键在于求课程集合相等的问题。 可以使用如下sql即可求出两个所修课程完全相同的同学的学号: select s1.sid,s2.sid fro
假设有一张成绩表(score):字段如下: sid:学生学号, cid:课程编号, score:成绩 求所修课程完全相同的同学的学号。这个问题其实关键在于求课程集合相等的问题。 可以使用如下sql即可求出两个所修课程完全相同的同学的学号:
select s1.sid,s2.sid from score s1 INNER JOIN score s2 ON (s1.cid=s2.cid and s1.sid < s2.sid) GROUP BY s1.sid,s2.sid HAVING count(*) = (select count(*) from score where s1.sid=sid) AND count(*) = (select count(*) from score where s2.sid=sid);
集合相等的问题可以衍生出如求与学号002同学所修课程完全相同的其它同学的学号和姓名:
select st.sid,st.sname from student st where st.sid in ( select sc.sc_sid from ( select s1.sid,s2.sid as sc_sid from score s1 INNER JOIN score s2 ON (s1.cid=s2.cid and s1.sid <> s2.sid and s1.sid='002') GROUP BY s1.sid,s2.sid HAVING count(*) = (select count(*) from score where sid=s1.sid) and count(*) = (select count(*) from score where sid=s2.sid) ) sc );