我需要一些有关 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 查询?
最佳答案
我喜欢用 group by
和 having
来做到这一点:
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,你可以加入教师姓名。
关于mysql - 从连接表中提取信息的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42298591/