我想知道一个用户是否有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)