如何让所有学生的名字都由老师教授,名字叫John?
学生
id
name
student_has_teacher
teacher_id
student_id
教师
id
name
答案 0 :(得分:4)
您必须使用Inner Joins。内部联接通过基于连接谓词组合两个表的列值来创建新的结果表。您的查询应该看起来像这样:
SELECT student.name
FROM student
INNER JOIN student_has_teacher ON (student_has_teacher.student_id = student.id)
INNER JOIN teacher ON (teacher.id = student_has_teacher.teacher_id)
WHERE teacher.name = 'John';
答案 1 :(得分:2)
SELECT s.name
FROM student s
INNER JOIN student_has_teacher st ON s.id = st.student_id
INNER JOIN teacher t ON st.teacher_id = t.id
WHERE t.name = 'John'
答案 2 :(得分:0)
下面的第一个查询假设student_has_teacher中可能存在重复记录,并且即使是这种情况也会避免导致重复结果:
select s.id, s.name
from student s
where s.id in (
select sht.student_id
from student_has_teacher sht
inner join teacher on sht.teacher_id = t.id
where t.name = 'John'
)
如果student_has_teacher中没有重复项,那么您可以使用联接,如下所示:
select s.id, s.name
from student s
inner join student_has_teacher sht on s.id = sht.student_id
inner join teacher on sht.teacher_id = t.id
where t.name = 'John'
答案 3 :(得分:0)
以下查询肯定会为您提供所需的结果。
SELECT st.name
FROM student AS st
LEFT JOIN student_has_teacher AS stte ON st.id = stte.student_id
LEFT JOIN teacher AS te ON stte.teacher_id = te.id
WHERE te.name = "John"