2014-09-25 60 views
0

如果你有下列表格:MYSQL - 找老師1和被給予的課程名稱2

course: 
    +---------------+---------------+ 
    |  id  |  Name  | 
    |---------------|---------------| 
    |  1  | Maths  | 
    |  2  | English  |   
    |  3  | Art   |   
    |  4  | Physics  |   
    |  5  | Psychology |   
    +-------------------------------+   

    course_teacher:         
    +----------------------+---------------------+   
    |  course_id  |  teacher_id  | 
    |----------------------|---------------------| 
    |  1    | 1     | 
    |  2    | 1     | 
    |  1    | 2     | 
    |  2    | 2     | 
    |  3    | 2     | 
    +----------------------v---------------------+ 

我怎樣才能獲得通過教師1和2

給出課程名稱列表我的嘗試:SELECT DISTINCT( COURSE_ID ) FROM course_teacher WHERE teacher_id IN (1,2);

但是,這種查詢過濾所有不過濾的雙重結果對教師1和2

+0

基本「加入的cheatsheet」,我不能推薦這還不夠:http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/ – tedder42 2014-09-25 21:59:05

回答

2
SELECT DISTINCT(name) FROM courses c 
INNER JOIN course_teachers ct ON c.id = ct.course_id 
WHERE ct.teacher_id = 1 OR ct.teacher_id = 2; 

http://sqlfiddle.com/#!2/8f7f9/6/0

如果你想只爲教師的課程,那麼它的相關性:

SELECT name FROM courses c 
INNER JOIN course_teachers ct ON c.id = ct.course_id 
WHERE ct.teacher_id = 1 OR ct.teacher_id = 2 GROUP BY c.id 
HAVING COUNT(c.id) = 2; 

http://sqlfiddle.com/#!2/8f7f9/7/0

+0

錯老師1不給我藝術 – botenvouwer 2014-09-25 22:05:47

+0

更新我的回答 – maszter 2014-09-25 22:10:54

+0

好吧,我已經找到了解決方案,但無論如何你看起來更好。謝謝! – botenvouwer 2014-09-25 22:12:17

0

發現我現在JOIN表:

SELECT vk1.`course_id` 
FROM `course_teacher` vk1, `course_teacher` vk2 
WHERE vk1.`teacher_id` =2 
AND vk2.`teacher_id` =10 
AND vk1.`course_id` = vk2.`course_id` 
GROUP BY vk1.`course_id` 

請注意,我沒有包含課程名稱!這需要一個額外的JOIN