Mysql 左连接后的内部连接返回null
我想返回每一行Mysql 左连接后的内部连接返回null,mysql,sql,Mysql,Sql,我想返回每一行p,如果没有ROLE\u ADMIN,则u.id和u.first\u name的值为空。当我执行此查询时,得到的结果为空。如果我使用left join而不是internal我会得到不正确的结果。如何筛选左连接,以便在没有匹配项的情况下,仍然返回p行,其中u.id和u.first\u name的值为空 注:我在末尾添加了p.id=13455,仅用于测试目的 select u.id, u.first_name, p.id from sub p left join oub oj
p
,如果没有ROLE\u ADMIN
,则u.id
和u.first\u name
的值为空。当我执行此查询时,得到的结果为空。如果我使用left join
而不是internal
我会得到不正确的结果。如何筛选左连接,以便在没有匹配项的情况下,仍然返回p行,其中u.id
和u.first\u 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;
使用左连接,如下所示
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;
我认为你想要的逻辑是:
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
所以我是这样解决的:
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;
我得到的结果与使用常规左连接时的结果相同。最后一个左连接返回null,但它之前的一个连接有一些值,因此它将返回所有结果,忽略最后一个连接筛选器。是否可以仅获取用户所在的行?我想获取所有用户,或者只返回一个p行,用户值为null。通过您的查询,我得到了所有空值用户和一个真实用户。