2015-07-13 135 views
6

我想返回一個在一個部門上課但不在另一個部門上的學生列表。這是我的查詢,由於某種原因,其結果是空白。如何查詢一個不包含MySQL中另一個集合中的任何成員的集合?

SELECT * 
FROM student 
JOIN transcript 
    ON student.id = transcript.studID 
JOIN course 
    ON transcript.crsCode = course.crsCode 
WHERE deptId = "CSCI" NOT IN 
     (
     SELECT student.name 
     FROM student 
     JOIN transcript 
      ON student.id = transcript.studID 
     JOIN course 
      ON transcript.crsCode = course.crsCode 
     WHERE deptId = "MATH" 
); 

這裏是什麼表是這樣的:

Student (id, name, address, status) 
Transcript (studId, crsCode, semester, grade) 
Courses (crsCode, deptId, crsName, descr) 
+0

例如http://forums.mysql.com/read.php?10507748,507839 – Strawberry

回答

2

要檢查兩個條件,你需要添加AND子句中查詢並檢查student.name是在你的子查詢作爲NOT IN

SELECT * 
FROM student 
JOIN transcript 
    ON student.id = transcript.studID 
JOIN course 
    ON transcript.crsCode = course.crsCode 
WHERE deptId = "CSCI" AND student.name NOT IN 
     (
     SELECT student.name 
     FROM student 
     JOIN transcript 
      ON student.id = transcript.studID 
     JOIN course 
      ON transcript.crsCode = course.crsCode 
     WHERE deptId = "MATH" 
); 
3

您可以使用兩個exists條件 - 一個用於要包含的部門和一個用於要排除的部門德。

SELECT s.* 
FROM student s 
WHERE EXISTS (SELECT * 
       FROM transcript t 
       JOIN courses c ON t.crsCode = c.crsCode 
       WHERE deptId = 'MATH' AND t.studId = s.id) AND 
     NOT EXISTS (SELECT * 
       FROM transcript t 
       JOIN courses c ON t.crsCode = c.crsCode 
       WHERE deptId = 'CSCI' AND t.studId = s.id) 
4

不使用子查詢: -

SELECT DISTINCT student.* 
FROM student 
JOIN transcript 
ON student.id = transcript.studID 
INNER JOIN course c1 
ON transcript.crsCode = c1.crsCode 
AND c1.deptId = 'CSCI' 
LEFT OUTER JOIN course c2 
ON transcript.crsCode = c2.crsCode 
AND c2.deptId = 'MATH' 
WHERE c2.crsCode IS NULL 

這是加盟學生成績單。然後它加入課程兩次,一次爲你想要的課程,一次爲你不想要的課程的左外連接。 WHERE子句檢查你不想要的課程是否匹配。

DISTINCT用於將結果限制爲單次出現次數。這可能沒有必要,但這取決於一個學生是否可以多次完成課程。

+0

當然,這只是選擇學生。 – Strawberry

+0

非常真實@Strawberry,但這是OP在問題中表示他們想要的。 – Kickstart

相關問題