如何连接3个表,根据条件限制查询,如果条件不满足则返回空列?

问题描述 投票:0回答:3

我目前有以下查询:

select * from people
LEFT JOIN addresses
ON people.id = addresses.id
LEFT JOIN pers
ON people.id = pers.pers_id
WHERE people.id =:id
AND addresses.is_primary = 'Y'

当然,如果给定的人没有地址is_primary ='Y',则查询不会返回任何结果。

如果没有is_primary ='Y',查询将返回多个地址。

相反,有没有办法在没有id的记录的情况下为所有地址字段返回空列,其中is_primary ='Y'?

sql oracle plsql oracle11g
3个回答
0
投票

你可以这样做 -

select *
  from people
  LEFT JOIN addresses
    ON people.pidm = addresses.pidm
   and addresses.is_primary = 'Y'
 RIGHT JOIN pers
    ON people.id = pers.pers_id
 WHERE people.id = :id

0
投票

用例何时

 select *,case when addresses.is_primary not in('Y') then 'primary address different' else addresses.is_primary end as  is_primary  from people
    LEFT JOIN addresses
    ON people.pidm = addresses.pidm
    RIGHT JOIN pers
    ON people.id = pers.pers_id
    WHERE people.id =:id

0
投票

我强烈建议你不要混合left joinright join。查询很难遵循。

相反,从要保留所有行的表开始。然后只使用left join。有时,您可能需要在on条款中加入条件。

在你的情况下:

select *
from people p left join
     addresses a
     on p.pidm = a.pidm and a.is_primary = 'Y' left join
     pers
     on p.id = pers.pers_id
where p.id = :id;
© www.soinside.com 2019 - 2024. All rights reserved.