【问题标题】:Joining tables when row matches multiple rows in other table当行匹配其他表中的多行时连接表
【发布时间】:2015-08-28 20:14:59
【问题描述】:

我想加入 3 个表(如下所示),但我不知道该怎么做:

表 1

vendor_id
---------
1
2
3
4

表 2

cuisine_type | vendor_id
------------------------
a            |1
b            |1
c            |1

表 3

cuisine_type|cuisine
--------------------
a           |pizza
b           |rice
c           |steak

我想加入 3 张桌子并得到这个:

vendor_id|cuisine_type|cuisine
------------------------------
1        |a, b, c     |pizza, steak, rice
2.......

我希望这是有道理的。我对 postgreSQL 很陌生,所以也许我错过了一些非常简单/明显的东西。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    这是一个简单的连接和基于 vendor_id 的聚合:

    select v.vendor_id, 
           string_agg(ct.cuisine_type, ', ') as cuisine_type,
           string_agg(c.cuisine, ', ') as cuisine
    from table_1 as v
       join table_2 as ct on v.vendor_id = ct.vendor_id
       join table_3 as c on ct.cuisine_type = c.cuisine_type
    group by v.vendor_id;
    

    【讨论】:

      【解决方案2】:

      您的表结构看起来有点奇怪。例如,为什么每种菜系只有一种菜系?通常,我希望供应商与美食相关联,然后每种美食都有一个类型。

      但是,这不是 this 问题。使用您提供的数据,您可以使用string_agg()

      select v.vendor_id, string_agg(cuisine_type, ', ') as cuisine_types,
             string_agg(cuisine, ', ') as cuisines
      from table1 v left join
           table2 v2c
           on v.vendor_id = v2c.vendor_id left join
           table3 c
           on c.cuisine_type = v2c.cuisine_type
      group by v.vendor_id;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-17
        • 2013-08-02
        • 2014-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        相关资源
        最近更新 更多