gpt4 book ai didi

postgresql - 在 postgresql View /函数中合并两个 json 对象

转载 作者:行者123 更新时间:2023-11-29 12:25:47 30 4
gpt4 key购买 nike

我在 postgress 中有以下 3 个表 ...

Employee (employee_id, ...)
Address (address_id, owner_id, ...)
Address_Component (address_id, key, value)

虽然地址组件有像......这样的数据

| 123 | province     | Toronto      |
| 123 | country | Canada |
| 123 | addressLine1 | some address |

员工可以有多个地址,每个地址与一个地址组件相关联。

我想将 address 作为 json 并将 address_component 作为嵌入地址对象中的另一个 json。

select emp.employee_id,
array_to_json(array_agg(row_to_json(adr))) as address,
json_object(array_agg(adrcomp.key), array_agg(adrcomp.value)) as address_component
FROM employee emp
LEFT JOIN address adr ON adr.owner_id = emp.employee_id
LEFT JOIN address_component adrcomp ON adr.address_id = adrcomp.address_id
WHERE employee_id = 'a6f49ab5-1769-4953-9b0e-6c12754d33c7'
GROUP BY emp.employee_id

有了这个,我能够正确地获取地址数组作为 json,同时我暂时将地址组件作为单独的结果。你能帮我把这个 address_component json 合并到 address json 数组的单个元素中,得到如下输出吗?

[{ address_id:"123", owner_id: "E1", address_component: {province:"", "country":"", addressLine1:""} }, { ... }]

最佳答案

您不能在同一级别上做所有事情,因为您要聚合两次。您需要从它自己的子查询中创建 address_component:

SELECT emp.employee_id,
jsonb_agg((
SELECT a FROM (
SELECT adr.address_id, adr.owner_id,
(SELECT json_object_agg(key, value)
FROM address_component
WHERE address_id = adr.address_id) AS address_component) a))
FROM employee emp
LEFT JOIN address adr ON adr.owner_id = emp.employee_id
WHERE employee_id = 'a6f49ab5-1769-4953-9b0e-6c12754d33c7'
GROUP BY emp.employee_id

关于postgresql - 在 postgresql View /函数中合并两个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126432/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com