arrays - 在 PostgreSQL 中:如何将包含 FK 的数组字段转换为引用表中的名称数组?
问题描述
我的数据库有一个产品表,如下所示:
PRODUCTS
----------------------------
id | name | suppliers
----------------------------
1 | widget | {1,2}
2 | gizmo | {1}
3 | geegaw | {3}
4 | tchotchke | null
该列包含属于供应商表的 IDsuppliers
数组 ( ):numeric[]
SUPPLIERS
------------
id | name
------------
1 | alpha
2 | beta
3 | gamma
如何编写一个查询,该查询将返回PRODUCTS
带有供应商名称数组而不是供应商 ID 号的 except 的内容?结果应如下所示:
-----------------------------------
id | name | suppliers
-----------------------------------
1 | widget | {'alpha','beta'}
2 | gizmo | {'alpha'}
3 | geegaw | {'gamma'}
4 | tchotchke | null
简洁有效的方法将是首选,但可读性/可理解性也很好。
编辑:这不是链接问题的副本,尽管该问题确实涉及unnest
操作,但它不会重新汇总结果。这个问题的答案对网站做出了新的贡献。
解决方案
select t1.id, t1.name, array_agg(s.Name) as Suppliers
from Products t1
left join lateral (
select unnest(suppliers) as supplierId from myProducts t2
where t1.id = t2.id) as t on true
left join Suppliers s on s.Id = t.supplierID
group by t1.id, t1.name;
我在想什么。这是一个更好的版本:
select p.id, p.name, array_agg(s.Name) as Suppliers
from (select *,unnest(suppliers) as supplierId from Products) p
left join Suppliers s on s.Id = p.supplierID
group by p.id, p.name;
推荐阅读
- reactjs - React JS 中的 Bing 地图 - 道具更改时组件不加载
- symfony - Symfony 4 实体生成器坏路径问题
- excel - 使用 excel vba,是否有一种简单的方法可以说“如果退出任何函数或子潜艇,则退出宏”?
- python - 为什么 SARIMA 在预测负增长时会出错?
- javascript - 如何使用 setCustomValidity() API 向时间表单添加错误消息
- scala - 一些 ScalaTest 套件没有被执行
- java - Request 类在哪里定义?
- php - sql查询在数据库中插入数据两次
- c++ - C++ 部分模板专业化:未声明的标识符错误
- python - 如何使用正则表达式在“/”之前或之后查找数字