我想知道一个用户是否有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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。