在 Join PostgreSQL 中取消嵌套数组

Unnesting array with in Join PostgreSQL

我有两个 table,其中一个有一个唯一的 ID 列和一个包含数组的列,这些数组为 Table B 中的唯一记录保存零个或多个标识符。我正在尝试显示使用每个项目的订单,但我无法想出一种方法来连接 table A 和 B,这样不仅每个订单或项目都有一行,而且所有订单都有很多商品

Table答:

OrderID   |      Items       |      name
----------+------------------+------------
order1    | {item1,item2}    |  "Bob's pizza order"
order2    | {item3,item1}    |  "Alice's breakfast order"

Table乙:

itemID   |      price     |      name
---------+----------------+------------
item1    |      2.95      |  "cheese"
item2    |      3.15      |  "tomato sauce"
item3    |      3.50      |  "eggs"

期望的输出类似于

ItemID   |     OrderID    |     name
---------+----------------+------------
item1    |     order1     |  "cheese"
item1    |     order2     |  "cheese"
item2    |     order1     |  "tomato sauce"
item3    |     order2     |  "eggs"

有谁知道如何取消嵌套 Table A 中的数组,这样我就可以使用所有项目将 A 和 B 与每个订单的每个项目的记录连接起来?

看起来 postgresSQL 有一些我不习惯的强大功能!

查看其他一些文档后,这可能具有您正在寻找的效果 -

with table_a (OrderID, Items) as
      (select 'order1', '{item1,item2,item4}' union all
       select 'order2', '{item3,item1}'
    )
,

trim as (
  select OrderID, Replace(Replace(Items, '{', ''),'}','') as Items
from table_a)

SELECT
OrderID,
unnest(string_to_array(Items, ',')) AS ItemID
from trim

如果 Items 列是一个真正的数组,您应该能够删除 trim CTE 并删除 string_to_array 函数。

整个事情看起来像-

with unnested_data as(
SELECT
 OrderID,
 unnest(Items) AS ItemID
FROM table_a)

SELECT
 a.ItemID,
 a.OrderID,
 b.name
FROM unnested_data AS a
JOIN table_b AS b
 on a.ItemID = b.itemID

要将每个项目作为一行,您需要取消嵌套数组(本质上是动态规范化模型):

select b.itemid, a.orderid, b.name
from table_a a 
  cross join unnest(a.items) as i(item) 
  join table_b b on i.item = b.itemid
order by b.itemid;

Online example