在postgresql视图/函数中合并两个json对象

时间:2016-06-30 14:41:04

标签: postgresql psql sql-view postgresql-9.5 postgresql-json

我在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 |

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

我希望将地址作为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合并到地址json数组的单个元素中,得到如下的输出吗?

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

1 个答案:

答案 0 :(得分:0)

由于您要聚合两次,因此无法在同一级别执行所有操作。您需要从自己的子查询中创建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