在另一个表的所有条目中查找数据库中列的条目

时间:2013-09-19 20:12:47

标签: mysql sql database sqlite postgresql

考虑数据库建模课程的以下模式:

部门(确实,姓名),

COURSE(cid,did,name,num,creditHours),

学生(sid,fname,lname,did)

ENROLLED_IN(eid,sid,cid)

列出每个COMP课程中注册的所有学生的名字和姓氏(DEPARTMENT.name =“COMP”)

2 个答案:

答案 0 :(得分:0)

尝试加入

SELECT s.* FROM STUDENT s
JOIN ENROLLED_IN e ON (s.sid = e.sid)
JOIN DEPARTMENT d ON(s.did = d.did)
JOIN COURSE c ON(d.did = c.did)
WHERE d.name="COMP"

答案 1 :(得分:0)

使用带有HAVING子句的GROUP BY来断言注册的COMP课程数量:

SELECT s.fname, s.lname
FROM STUDENT s
JOIN ENROLLED_IN e ON s.sid = e.sid
JOIN COURSE c ON e.cid = c.cid
JOIN DEPARTMENT d ON c.did = d.did
WHERE d.name = 'COMP'
GROUP BY 1, 2
HAVING COUNT(*) = (
    SELECT COUNT(*)
    FROM COURSE c
    JOIN DEPARTMENT d ON c.did = d.did
    WHERE d.name = 'COMP')