【问题标题】:Inner join after left join to return null左连接后的内连接返回null
【发布时间】:2020-08-10 09:07:18
【问题描述】:

我想返回每个p 行,如果u.idu.first_name 没有ROLE_ADMIN,则它们具有空值。当我执行此查询时,我得到空结果。如果我使用 left join 而不是 inner 我会得到不正确的结果。如何过滤左连接,以便如果没有匹配项,我仍然会返回 p 行,其中 u.idu.first_name 的值为空?

注意:我在末尾添加了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;

【问题讨论】:

    标签: mysql sql


    【解决方案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;
    

    【讨论】:

    • 我得到与使用常规左连接时相同的结果。最后一个左连接返回 null 但之前的一个有一些值,因此它将返回所有结果,忽略最后一个连接过滤器。
    【解决方案2】:

    我认为你想要的逻辑是:

    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
    

    【讨论】:

    • 是否可以只获取用户所在的行?我想获取所有用户或只返回一个 p 行,其中 null 作为用户值。通过您的查询,我得到了所有具有空值的用户和一个真实用户。
    【解决方案3】:

    所以我这样解决了:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多