Select 来自三个 table 的数据,仅当其中一个引用了 parent table
Select data from three tables only if one of them has reference to parent table
我有三个table人,他的车,他的房子。如果其中一个孩子(汽车,房子)table 参考了 parent(人),我需要 select 个人有车有房。
我试过加入,但不知道如何在这种情况下使用 OR。
Table person
id name
1 Mark
2 David
3 Mike
4 Andrew
Table house
id city person
1 Moscow 1
2 Chicago 1
3 New York 2
4 Boston 2
Table car
id brand person
1 bmw 4
2 opel 4
3 toyota 2
4 volvo 2
结果应该是
name city car
Mark Moscow Chicago
David New York Boston toyota volvo
Andrew bmw opel
您可以 left join
两次并确保其中一个连接成功。剩下的就是聚合:
select
p.name,
string_agg(distinct h.city, ' ' order by h.city) cities,
string_agg(distinct c.brand, ' ' order by c.brand) brands
from person p
left join house h on h.person = p.id
left join car c on c.person = p.id
where c.person is not null or h.person is not null
group by p.id, p.name
name | cities | brands
:----- | :-------------- | :-----------
Mark | Chicago Moscow | null
David | Boston New York | toyota volvo
Andrew | null | bmw opel
我有三个table人,他的车,他的房子。如果其中一个孩子(汽车,房子)table 参考了 parent(人),我需要 select 个人有车有房。
我试过加入,但不知道如何在这种情况下使用 OR。
Table person
id name
1 Mark
2 David
3 Mike
4 Andrew
Table house
id city person
1 Moscow 1
2 Chicago 1
3 New York 2
4 Boston 2
Table car
id brand person
1 bmw 4
2 opel 4
3 toyota 2
4 volvo 2
结果应该是
name city car
Mark Moscow Chicago
David New York Boston toyota volvo
Andrew bmw opel
您可以 left join
两次并确保其中一个连接成功。剩下的就是聚合:
select
p.name,
string_agg(distinct h.city, ' ' order by h.city) cities,
string_agg(distinct c.brand, ' ' order by c.brand) brands
from person p
left join house h on h.person = p.id
left join car c on c.person = p.id
where c.person is not null or h.person is not null
group by p.id, p.name
name | cities | brands :----- | :-------------- | :----------- Mark | Chicago Moscow | null David | Boston New York | toyota volvo Andrew | null | bmw opel