3

我有以下表格:

Schools
Teachers
Courses
XRefSchoolsTeachers
XRefCoursesTeachers

现在我正在尝试获取提供该课程的大学所有教师的名单,这些教师不教授该课程。到目前为止,我有:

SELECT *
FROM Courses
INNER JOIN XRefSchoolsTeachers
    ON Courses.SchoolID = XRefSchoolsTeachers.SchoolID

这给了我提供该课程的学校所有教师的 ID,但现在我需要删除所有不反对该课程 ID 的教师 ID XRefCoursesTeachers。我在这里查看了另一个关于如何删除不在另一个列表中的东西的问题,我需要一个左连接。但我觉得我也需要一个内部加入,这样我才能得到那所学校的老师,他们已经不在名单上><

例如

SELECT *
FROM Courses
INNER JOIN XRefSchoolsTeachers
    ON Courses.SchoolID = XRefSchoolsTeachers.SchoolID
LEFT JOIN XRefCoursesTeachers
    ON (XRefCoursesTeachers.TeacherID = XRefSchoolsTeachers.TeacherID
     AND XRefCoursesTeachers.CourseID = Courses.ID)
WHERE Courses.ID = ? AND XRefSchoolsTeachers.TeacherID IS NULL

会给我任何其他学校任何其他课程的所有老师——不是我想要的。我想要所有可以教门课但不能教的老师。

就像我需要在 上进行内部连接XRefCourseTeachers.CourseID = Courses.ID,然后在同一个XRefCourseTeachersusing实例上进行左连接,TeacherID以便我可以挑选出NULL结果。但我不知道如何做到这一点。

这怎么可能?我采取了正确的方法吗?

4

2 回答 2

1
SELECT *
FROM Courses
INNER JOIN XRefSchoolsTeachers
    ON Courses.SchoolID = XRefSchoolsTeachers.SchoolID
left join XRefCoursesTeachers
    on XRefCoursesTeachers.TeacherID = XRefSchoolsTeachers.TeacherID
where 
    XRefCoursesTeachers.TeacherID is null
    and
    Cousers.ID = ?

或者

SELECT *
FROM Courses
INNER JOIN XRefSchoolsTeachers
    ON Courses.SchoolID = XRefSchoolsTeachers.SchoolID
where 
    XRefCoursesTeachers.TeacherID not in (
        select TeacherID
        from XRefCoursesTeachers
        where XRefCoursesTeachers.CourseID = Courses.ID
    )
    and
    Courses.ID = ?
于 2012-09-18T13:02:06.543 回答
1

找到了解决方案:

SELECT *
FROM Courses
INNER JOIN XRefSchoolsTeachers
    ON Courses.SchoolID = XRefSchoolsTeachers.SchoolID
LEFT JOIN XRefCoursesTeachers
    ON (XRefCoursesTeachers.TeacherID = XRefSchoolsTeachers.TeacherID AND XRefCoursesTeachers.CourseID = Courses.ID)
WHERE 
        XRefCoursesTeachers.TeacherID IS NULL
    AND
        Cousers.ID = ?
于 2012-09-19T12:28:07.783 回答