MYSQL - 获得老师1和2给出的课程名称

时间:2014-09-25 21:44:59

标签: mysql

如果您有以下表格:

   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上过滤的双重结果。

2 个答案:

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

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