用于从连接表

时间:2017-02-17 12:58:04

标签: mysql sql database postgresql

我需要一些SQL查询的帮助,我甚至不知道如何命名这种SQL查询模式...我有以下简化表:

teachers: 
  ID | NAME
  1  | john
  2  | paul

teachers_subjects: 
  TEACHER_ID | SUBJECT_ID
  1          | 42
  1          | 43
  2          | 43


subjects: 
   ID | NAME
   42 | english
   43 | french

这很简单:老师可以教许多科目。现在,我需要找到所有可以教授“英语”和“法语”(恰好是“约翰”)的老师。那个SQL查询是什么?

3 个答案:

答案 0 :(得分:4)

我喜欢使用group byhaving

执行此操作
select ts.teacher_id
from teachers_subjects ts join
     subjects s
     on ts.subject_id = s.id
where s.name in ('English', 'French')
group by ts.teacher_id
having count(*) = 2;  -- the teacher teaches both languages

注意:如果您希望在输出中而不是ID,则可以加入教师姓名。

答案 1 :(得分:2)

一种可能的解决方案是创建一个单独的查询,以获得教英语的老师和教法语的老师。如果您同时拥有这两个集合,则可以使用intersect命令查找两个集合中存在的集合。

相应的sql代码如下所示:

(SELECT teachers.name
FROM teachers, teachers_subjects, subjects
WHERE teachers.id = teachers_subject.id AND teachers_subjects.subject_id = subjects.id and subjects.name = "english")
INTERSECT
(SELECT teachers.name
FROM teachers, teachers_subjects, subjects
WHERE teachers.id = teachers_subject.id AND teachers_subjects.subject_id = subjects.id and subjects.name = "french")

答案 2 :(得分:0)

JOIN所有表格。像

这样的东西
select t.Name
from teachers t
join teachers_subjects ts on t.id = ts.teacher_id
join subject s1 on ts.subject_id = s1.id
join subject s2 on ts.subject_id = s2.id
where s1.NAME = 'English' and s2.NAME = 'French'