1

我有一个很难描述的简单问题(至少对我来说)。

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

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

学生(sid、fname、lname、did)

ENROLLED_IN (eid, sid, cid)

什么查询可以找到参加 course.name=Math" 和 "Science" 的学生的 sid?

对不起,我问了一个类似(更简单)的问题,以为我可以弄清楚其余的问题,但我无法:https ://stackoverflow.com/questions/18902489/how-to-find-entries-in-database-that-满足多重匹配

4

1 回答 1

3

正如另一页所建议的,您需要对同一张表进行两次 JOIN。但是由于您想使用名称而不是 cid,因此您可以根据注册数据加入课程。

SELECT DISTINCT s.sid
FROM STUDENT s
INNER JOIN ENROLLED_IN e ON e.sid = s.sid
INNER JOIN COURSE c ON c.cid = e.cid AND c.Name = 'Math'
INNER JOIN COURSE c2 ON c2.cid = e.cid AND c2.Name = 'Science'

如果您需要整个学生记录,那么...

SELECT STUDENT.*
FROM STUDENT
INNER JOIN
  (SELECT DISTINCT s.sid
   FROM STUDENT s
   INNER JOIN ENROLLED_IN e ON e.sid = s.sid
   INNER JOIN COURSE c ON c.cid = e.cid AND c.Name = 'Math'
   INNER JOIN COURSE c2 ON c2.cid = e.cid AND c2.Name = 'Science'
) t0 ON t0.sid = STUDENT.sid

编辑代替 DISTINCT 你也可以使用 GROUP BY,ala

   SELECT s.sid
   FROM STUDENT s
   INNER JOIN ENROLLED_IN e ON e.sid = s.sid
   INNER JOIN COURSE c ON c.cid = e.cid AND c.Name = 'Math'
   INNER JOIN COURSE c2 ON c2.cid = e.cid AND c2.Name = 'Science'
   GROUP BY s.sid

编辑而不是使用两个连接,您可以使用HAVING子句

SELECT s.sid
FROM STUDENT s
INNER JOIN ENROLLED_IN e ON e.sid = s.sid
INNER JOIN COURSE c ON c.cid = e.cid
WHERE c.Name IN ('Math', 'Science')
GROUP BY s.sid
HAVING COUNT(*) = 2
于 2013-09-19T19:32:02.473 回答