2012-09-18 73 views
3

我有以下表格:MYSQL加入拼圖:內部和左連接在同一時間

Schools 
Teachers 
Courses 
XRefSchoolsTeachers 
XRefCoursesTeachers 

現在我想在課程的,所提供的大學獲得所有教師的列表,它不在教這門課程。到目前爲止,我有:

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

這給了我所有的老師的ID在該課程在所提供的學校,但現在我要刪除哪些是不反對的,該ID老師的所有ID當然在XRefCoursesTeachers。我看着another question here關於如何刪除不在另一個列表上的東西,我需要一個左連接。但我覺得我還需要一個內部加入,以便我只從該學校獲得不在列表中的教師> <

例如,

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,然後左連接上使用TeacherID,這樣我可以挑出NULL結果XRefCourseTeachers相同的實例。但我不知道該怎麼做。

這怎麼可能?我採取了正確的方法嗎?

+0

看來你缺少一個表 - CoursesSchools? – podiluska

+0

不完全。事實證明,每門課程只能在一所學校教授,因此「課程」表包含一個「SchoolID」列。有更多的表可能會更好,但現在它只是一個列。 – Sophie

+0

無需重新發布Clodoaldo提供的相同解決方案。相反,你應該投票並接受他的解決方案 – Sami

回答

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 = ? 
+0

你是對的... – Sami

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 = ? 
+0

當然!!〜我忘記了內部連接也可以在'WHERE'子句中完成:D謝謝 – Sophie

+0

仔細檢查,你的第一個表達式基本上就是我在問題中提到的,它不起作用 – Sophie