左联接后的内部联接返回null

时间:2020-08-10 09:07:18

标签: mysql sql

我想返回每p行,如果u.idu.first_name没有ROLE_ADMIN,则返回空值。当我执行此查询时,我得到的结果为空。如果我使用left join而不是inner,则会得到错误的结果。如何过滤左联接,以便在没有任何匹配的情况下仍返回u.idu.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;

3 个答案:

答案 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;