我想返回一个在一个系上上课但不在另一个系类的学生的 list 。这是我的查询,由于某种原因其结果空白。

 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)

最佳答案

不使用子查询:

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

这是学生反对成绩单。然后,它针对类(class)加入两次,一次针对您想要的类(class),一次左外加入针对您不想要的类(class)。 WHERE子句检查您不希望的类(class)是否匹配。

DISTINCT用于将结果限制为单次出现。这可能不是必需的,但这取决于单个学生是否可以完成多次类(class)。

10-08 16:44