我的 posts
表中有以下 JSONB 字段:comments
。
comments
看起来像这样:
[
{"id": 1, "text": "My comment"},
{"id": 2, "text": "My other comment"},
]
我想选择一些关于每条评论的信息。
SELECT comments->?????? FROM posts WHERE posts.id = 1;
有没有办法让我只选择 JSON 的 id
字段。例如。我的 SQL 查询的结果应该是:
[{"id": 1}, {"id": 2}]
谢谢!
最佳答案
您可以使用 jsonb_to_recordset
将每条评论拆分成自己的行。只有您指定的列才会出现在该行中,因此您可以使用它来仅保留 id
列。然后,您可以使用 json_agg
将一篇文章的评论聚合到一个数组中:
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}]
关于sql - 数组的 JSONB 子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452206/