【问题标题】:Select data from three tables only if one of them has reference to parent table仅当其中一个表引用父表时才从三个表中选择数据
【发布时间】:2019-11-05 07:37:56
【问题描述】:

我有三桌人,他的车,他的房子。如果其中一个孩子(汽车,房子)表参考了父母(人),我需要选择有他的汽车和房子的人。

我尝试过加入,但不知道在这种情况下如何使用 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

【问题讨论】:

    标签: sql postgresql postgresql-11


    【解决方案1】:

    您可以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
    

    Demo on DB Fiddle

    姓名 |城市|品牌 :----- | :---------------- | :----------- 马克 |芝加哥莫斯科 | 大卫 |波士顿纽约 |丰田沃尔沃 安德鲁 | |宝马欧宝

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多