假设我有一个表Products
,如下所示:
category | items
-----------------
fruit | {"apple", "banana"}
vegetable| {"carrot"}
和表Prices
看起来像:
name | price
----------------
apple | 1
banana | 2
carrot | 3
获得输出的最简单方法是:
category | prices
-----------------
fruit | {1, 2}
vegetable| {3}
随意使用CTE或任何其他细节,使查询易于阅读。
答案 0 :(得分:1)
使用unnest()
获取items
数组的元素,这些元素可以与names
表的prices
结合使用。最后,prices
应按category
分组:
select category, array_agg(price) as prices
from products
cross join unnest(items) u(item)
join prices on name = item
group by category
order by category;
category | prices
-----------+--------
fruit | {1,2}
vegetable | {3}
(2 rows)