postgres 11.6 - 从 JSON 数组创建 JSON Objects 的数组
postgres 11.6 - Creating array of JSON Objects from JSON array
我这里有以下架构:http://sqlfiddle.com/#!17/5c73a/1
我想创建一个查询,结果如下所示:
id | tags
_________________________________
1. | [{"id": "id", "title": "first"}, {"id": "id", "title": "second"},{"id": "id", "title": "third"}]
2 | [{"id": "id", "title": "fourth"}, {"id": "id", "title": "fifth"},{"id": "id", "title": "sixth"}]
想法是构建一个数组,数组的每一行都有一个object,重要的是标题变量
您需要取消嵌套数组,然后将其聚合回来:
select t.id, jsonb_agg(jsonb_build_object('id', 'id', 'title', tg.title))
from things t
cross join jsonb_array_elements(tags) as tg(title)
group by t.id;
我这里有以下架构:http://sqlfiddle.com/#!17/5c73a/1
我想创建一个查询,结果如下所示:
id | tags
_________________________________
1. | [{"id": "id", "title": "first"}, {"id": "id", "title": "second"},{"id": "id", "title": "third"}]
2 | [{"id": "id", "title": "fourth"}, {"id": "id", "title": "fifth"},{"id": "id", "title": "sixth"}]
想法是构建一个数组,数组的每一行都有一个object,重要的是标题变量
您需要取消嵌套数组,然后将其聚合回来:
select t.id, jsonb_agg(jsonb_build_object('id', 'id', 'title', tg.title))
from things t
cross join jsonb_array_elements(tags) as tg(title)
group by t.id;