MySQL SELECT连接3个表,其中包含所有行的条件

时间:2013-07-26 02:53:26

标签: mysql join

我需要一些帮助来正确创建我的选择......

这是我的表格:

**teacher** :
id
name

**classroom** :
id
teacher_id

**students** :
id
name
classroom_id
status

我正在尝试选择所有有教室的老师。 只有当所有学生的状态> gt时,才能选择课堂。 10 ...

如果学生的状态为5,例如教室可能不会被选中,因此教师可能不会被选中(除了他有另一个OK教室)

1 个答案:

答案 0 :(得分:1)

试试这个:

select * from teacher t
inner join classroom c on t.id=c.teacher_id
inner join 
(select * from students 
group by classroom_id having classroom_id not in 
(select distinct classroom_id from students where status<=10)) s 
on s.classroom_id=c.id

更新: 从你的评论我认为上面的查询应该工作,但你可以测试这个查询:

select * from teacher t where id in
   (select distinct teacher_id from classroom where id in
       (select distinct classroom_id from students 
        group by classroom_id having classroom_id not in 
          (select distinct classroom_id from students where status<=10)
        )
    )