【发布时间】:2018-04-26 19:13:18
【问题描述】:
我的问题和这个有点类似:
How to join jsonb array elements in Postgres?
但我需要填写一些嵌套数组。为简单起见,我只有 1 个表:
CREATE table tester(
id int,
name text,
d jsonb
)
INSERT INTO tester(id, name, d) VALUES
('1', 'bob', '[
{
"employees": [{"id":2},{"id":3},{"id":4}],
"coworkers": [{"id":5},{"id":6}]
},
{
"employees": [{"id":3},{"id":4}],
"coworkers": [{"id":5}]
}
]'::jsonb),
('2', 'barb', '[
{
"employees": [{"id":3}],
"coworkers": []
},
{
"employees": [{"id":3},{"id":4}],
"coworkers": [{"id":5, "id":3}]
}
]'::jsonb),
('3', 'ann', '[]'::jsonb),
('4', 'jeff', '[]'::jsonb),
('5', 'rachel', '[]'::jsonb),
('6', 'ryan', '[]'::jsonb);
见:http://sqlfiddle.com/#!17/7c7ef/12/0
我正在尝试简单地为每个同事和员工添加名称,以便 bob 看起来像:
[
{
"employees": [{"id":2, "name":"barb"},{"id":3, "name":"ann"},{"id":4, "jeff"}],
"coworkers": [{"id":5, "name":"rachel"},{"id":6, "name":"ryan"}]
},
{
"employees": [{"id":3, "name":"ann"},{"id":4, "name":"jeff"}],
"coworkers": [{"id":5, "name":"rachel"}]
}
]
到目前为止,我有:
SELECT c.person person
FROM tester
LEFT JOIN LATERAL(
SELECT jsonb_agg(
jsonb_build_object(
'employees', c.wrk->'employees',
'coworkers', c.wrk->'coworkers'
)
) AS person
FROM jsonb_array_elements(tester.d) AS c(wrk)
) c ON true
返回除名称之外的所有内容:
[{"coworkers": [{"id": 5}, {"id": 6}], "employees": [{"id": 2}, {"id": 3}, {"id": 4}]}, {"coworkers": [{"id": 5}], "employees": [{"id": 3}, {"id": 4}]}]
[{"coworkers": [], "employees": [{"id": 3}]}, {"coworkers": [{"id": 3}], "employees": [{"id": 3}, {"id": 4}]}]
(null)
(null)
(null)
(null)
请注意对象列表:它们是独立的对象,而不仅仅是一个大对象。
"(null)" s/b 是一个空白数组 "[]"。
【问题讨论】:
-
附加服务功能可能更简单:dbfiddle.uk/…
-
我认为您需要为每个同事和员工提供两个横向连接
标签: json postgresql aggregate-functions jsonb postgresql-9.6