数组的 JSONB 子集

JSONB subset of array

我的 posts table 上有以下 JSONB 字段:comments

comments 看起来像这样:

[
{"id": 1, "text": "My comment"},
{"id": 2, "text": "My other comment"},
]

我想select关于每条评论的一些信息。

SELECT comments->?????? FROM posts WHERE posts.id = 1;

有没有办法让我 select 仅 JSON 的 id 字段。例如。我的 SQL 查询的结果应该是:

[{"id": 1}, {"id": 2}]

谢谢!

您可以使用 jsonb_to_recordset 将每条评论拆分成自己的行。只有您指定的列才会出现在该行中,因此您可以使用它来仅保留 id 列。然后,您可以使用 json_agg:

将一个 post 的评论聚合到一个数组中
select  json_agg(c)
from    posts p
cross join lateral
        jsonb_to_recordset(comments) c(id int)  -- Only keep id
where   p.id = 1

这导致:

[{"id":1},{"id":2}]

Example at db-fiddle.com

您可以使用 json_build_object + json_agg

select json_agg(json_build_object('id',j->>'id'))
from  posts cross join jsonb_array_elements(comments) as j
where (j->>'id')::int = 1;

DEMO