如何从两边自我加入具有一系列值的表格?

时间:2017-02-23 13:41:41

标签: sql

有一个名为teachers的表格,其中详细列出了包含teacher_idrole_codevisit_tutorclass_code列的教师。如果role_code'CT'visit_tutornull,则教师是班级的常规教师。如果visit_tutor不是null,则他是班级的访问教师。

如何通过teacher_id class_code以及'AA' class_code访问班级老师,获取'BB'教师的常规教师列表?

以下代码引发错误,因为第一个子查询返回多行:

select * from teachers where (
   select teacher_id from teachers t1 where t1.role_code='CT' and t1.class_code='AA'
) in (
   select teacher_id from teachers t2 where t2.visit_tutor is not null and t2.class_code='BB'
);

1 个答案:

答案 0 :(得分:0)

那不是如何加入......

尝试:

select t1.*
from teachers t1
inner join teachers t2
on t1.teacher_id = t2.teacher_id
where t1.role_code='CT' and t1.class_code='AA'
and t2.visit_tutor is not null and t2.class_code='BB'