简体   繁体   中英

How to self-join a table with a range of values from both sides?

There is a table called teachers with details of teachers with columns teacher_id , role_code , visit_tutor and class_code . A teacher is a regular teacher of a class if role_code is 'CT' and visit_tutor is null . He is a visiting teacher of a class if visit_tutor is not null .

How to get the list of teacher_id s of teachers who are regular teachers of class with class_code 'AA' and visiting teacher of class with class_code 'BB' ?

The following code is throwing an error because the first subquery is returning multiple rows:

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

That's not how to join...

Try:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM