Home > Database > Mysql Tutorial > SQL问题:集合相等

SQL问题:集合相等

WBOY
Release: 2016-06-07 16:14:41
Original
2032 people have browsed it

假设有一张成绩表(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);
Copy after login

集合相等的问题可以衍生出如求与学号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 );
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template