在Postgres中,是否有一种方法可以执行left join
由联结表链接的表之间的链接,并对链接的表进行一些过滤?
说,我有两个表,humans
和pets
,我想执行一个查询,其中有人类ID和宠物的名字。如果存在人类ID,但是他们没有宠物叫,我仍然希望返回人类的行。
如果我有一个从FKpets
到FK的关系humans
,这将起作用:
select h.*, p.*
from humans as h
left join pets as p on p.human_id = h.id and p.name = 'fluffy'
where h.id = 13
然后我将讨论人类13的详细信息以及蓬松的值。另外,如果人类13没有一个名为“蓬松”的宠物,那么我会得到一行包含人类13的值,并且该宠物列的值为空。
但是,我没有直接的FK关系,humans
并且在和之间有一个联结表pets
,因此我正在尝试执行以下查询:
select h.*, p.*
from humans as h
left join humans_pets_junction as j on j.human_id = h.id
left join pets as p on j.pet_id = p.id and p.name = 'fluffy'
where h.id = 13
它返回人类13的所有宠物的行,除了蓬松的行以外,它们的列为空。
如果我添加p.name = 'fluffy'
到该WHERE
子句中,则将所有空行过滤掉,但是这也意味着如果人类13根本没有一个名为蓬松的宠物,我将获得0行。
有没有一种方法可以复制FK样式的行为left join
,但是当与联结表一起使用时?
一种方法是在where
子句中进行比较:
select h.*, p.*
from humans as h left join
humans_pets_junction as j
on j.human_id = h.id left join
pets as p
on j.pet_id = p.id and p.name = 'fluffy'
where h.id = 13 and (p.name = 'fluffy' or p.id is null);
或者,将联结表和pets表作为子查询或CTE连接:
select h.*, p.*
from humans h left join
(select j.*
from humans_pets_junction j join
pets p
on j.pet_id = p.id and p.name = 'fluffy'
) pj
on pj.human_id = h.id
where h.id = 13;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句