我想知道用户是否在2个相关表中的 任何 一个条目。
表
USER (user_id) EMPLOYEE (id, user_id) STUDENT (id, user_id)
用户可以有一个雇员和/或学生的条目。如何在一个查询中获取该信息?我试过了:
select * from [user] u inner join employee e on e.user_id = case when e.user_id is not NULL then u.user_id else null end inner join student s on s.user_id = case when s.user_id is not NULL then u.user_id else null end
但是它将仅返回在两个表中都有条目的用户。
您可以使用外部联接:
select * from USER u left outer join EMPLOYEE e ON u.user_id = e.user_id left outer join STUDENT s ON u.user_id = s.user_id where s.user_id is not null or e.user_id is not null
或者(如果您对EMPLOYEE或STUDENT表中的数据不感兴趣)
select * from USER u where exists (select 1 from EMPLOYEE e where e.user_id = u.user_id) or exists (select 1 from STUDENT s where s.user_id = u.user_id)