我想返回每p
行,如果u.id
和u.first_name
没有ROLE_ADMIN
,则返回空值。当我执行此查询时,我得到的结果为空。如果我使用left join
而不是inner
,则会得到错误的结果。如何过滤左联接,以便在没有任何匹配的情况下仍返回u.id
和u.first_name
为空值的p行?
注意:我在末尾添加了p.id = 13455
只是出于测试目的。
select u.id, u.first_name, p.id
from sub p
left join oub oj on oj.id = p.sub_id
left join jhi_user u on u.oub_id= oj.id
inner join jhi_user_authority ua on ua.user_id = u.id where ua.authority_name = 'ROLE_ADMIN' and p.id = 13544;
答案 0 :(得分:1)
使用左联接,如下所示
select u.id, u.first_name, p.id
from sub p
left join oub oj on oj.id = p.sub_id
left join jhi_user u on u.oub_id= oj.id
left join
( select * from
jhi_user_authority where authority_name = 'ROLE_ADMIN'
) ua on ua.user_id = u.id
where p.id = 13544;
答案 1 :(得分:1)
我认为您想要的逻辑是:
select
ua.user_id,
case when ua.user_id is not null then u.first_name end as first_name,
p.id
from sub p
left join oub oj
on oj.id = p.sub_id
left join jhi_user u
on u.oub_id= oj.id
left join jhi_user_authority ua
on ua.user_id = u.id
and ua. authority_name = 'ROLE_ADMIN'
and u.id is not null
答案 2 :(得分:0)
所以我这样解决了:
select u.id, u.first_name, p.id
from sub p
left join oub oj on oj.id = p.sub_id
left join jhi_user u on u.id =
(select ru.id from jhi_user ru inner join jhi_user_authority rua on rua.user_id = ru.id and rua.authority_name = 'ROLE_ADMIN' where ru.oub_id= oj.id)
where p.id = 18774;