MYSQL加入拼图:内部和左侧连接同时进行

时间:2012-09-18 12:32:58

标签: mysql join

我有以下表格:

Schools
Teachers
Courses
XRefSchoolsTeachers
XRefCoursesTeachers

现在我正在努力获得该课程所提供的所有教师名单,这些教师并没有教授该课程。到目前为止,我有:

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

它给了我提供课程的学校所有教师的ID,但现在我需要删除XRefCoursesTeachers中与该课程的ID不相符的所有教师ID。我查看another question here关于如何删除不在另一个列表中的内容,我需要一个左连接。但我觉得我也需要一个内部联接,所以我只能从那所学校的老师那里找到不在名单上的老师><

e.g。

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上的内部联接,然后使用XRefCourseTeachersTeacherID的同一个实例上左联接,以便我可以选择{{1结果。但我不明白该怎么做。

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

2 个答案:

答案 0 :(得分: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 = ?

答案 1 :(得分: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 = ?