PostgreSql 格式的 jsonb 数组
PostgreSql format jsonb array
找不到合适的查询来格式化 postgres 中的 jsonb 输出
我在 table.
中有一个 jonb 专栏
Table: Users
id| posts
--------
1 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]
2 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]
如何 select 帖子列只包含某些字段?类似于:
id| posts
--------
1 | [{'title':'', 'description': ''}, ...]
2 | [{'title':'', 'description': ''}, ...]
有什么想法吗?
PS: postgres的版本是最新的12,13,14 ...
您可以考虑使用 json_to_record_set
为帖子中的每个数组元素提取所需的列,然后再由用户 id
汇总结果以获得所需的元素。
查询#1
SELECT
u.id,
json_agg(
json_build_object(
'title',p.title,
'description',p.description
)
) as posts
FROM
users u,
json_to_recordset(u.posts) as p(
title text,
is_published text,
description text,
some_col text
)
GROUP BY
u.id
ORDER BY
u.id;
id
posts
1
[{"title":"","description":""}]
2
[{"title":"","description":""}]
或更短
查询 #2
SELECT
u.id,
json_agg(p) as posts
FROM
users u,
json_to_recordset(u.posts) as p(
title text,
description text
)
GROUP BY
u.id
ORDER BY
u.id;
id
posts
1
[{"title":"","description":""}]
2
[{"title":"","description":""}]
或
查询 #3
SELECT
u.id,
(
SELECT
json_agg(p.*)
FROM json_to_recordset(u.posts) as p(
title text,
description text
)
) as posts
FROM
users u;
让我知道这是否适合你。
找不到合适的查询来格式化 postgres 中的 jsonb 输出 我在 table.
中有一个 jonb 专栏Table: Users
id| posts
--------
1 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]
2 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]
如何 select 帖子列只包含某些字段?类似于:
id| posts
--------
1 | [{'title':'', 'description': ''}, ...]
2 | [{'title':'', 'description': ''}, ...]
有什么想法吗?
PS: postgres的版本是最新的12,13,14 ...
您可以考虑使用 json_to_record_set
为帖子中的每个数组元素提取所需的列,然后再由用户 id
汇总结果以获得所需的元素。
查询#1
SELECT
u.id,
json_agg(
json_build_object(
'title',p.title,
'description',p.description
)
) as posts
FROM
users u,
json_to_recordset(u.posts) as p(
title text,
is_published text,
description text,
some_col text
)
GROUP BY
u.id
ORDER BY
u.id;
id | posts |
---|---|
1 | [{"title":"","description":""}] |
2 | [{"title":"","description":""}] |
或更短
查询 #2
SELECT
u.id,
json_agg(p) as posts
FROM
users u,
json_to_recordset(u.posts) as p(
title text,
description text
)
GROUP BY
u.id
ORDER BY
u.id;
id | posts |
---|---|
1 | [{"title":"","description":""}] |
2 | [{"title":"","description":""}] |
或
查询 #3
SELECT
u.id,
(
SELECT
json_agg(p.*)
FROM json_to_recordset(u.posts) as p(
title text,
description text
)
) as posts
FROM
users u;
让我知道这是否适合你。