2017-02-17 197 views
0

我需要一些幫助的SQL查詢中提取信息,我甚至不知道如何命名這種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查詢呢?

+1

您在使用MySQL或PostgreSQL? (不要標記不涉及的產品。) – jarlh

+0

使用該表格數據,預期結果是什麼? (這裏也指定爲格式化文本。) – jarlh

+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。

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' 
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")