sql - 数组的 JSONB 子集

标签 sql json postgresql activerecord jsonb

我的 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}]

Example at db-fiddle.com

关于sql - 数组的 JSONB 子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452206/

相关文章:

sql - Hive sql : count and avg

sql - 在同一 DataResult 上加入 Found 和 Not Fund 记录

python - 为什么不能用urlencode编码json格式的数据?

json - 无法验证 CloudFormation 中的以下目标配置

postgresql - 如何在 Postgres oid 列中插入二进制数据

postgresql - SQL 正则表达式量词操作数在 postgres 9.5.16 上无效,适用于 9.6.12

sql - SQL中的树深度

mysql - 我应该删除我的 MySQL 记录,还是应该有一个标志 "is_deleted"?

json - Dart boolean在更新后保持不变

sql - 在 Postgres 中查询时使用通配符或 "in list"