【问题标题】:PostgreSql format jsonb arrayPostgreSql 格式 jsonb 数组
【发布时间】:2021-09-09 19:12:19
【问题描述】:

在 postgres 中找不到合适的查询来格式化 jsonb 输出 我的表中有一个 jonb 列。

Table: Users
id| posts
--------
1 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]
2 | [{'title': '', 'is_published': '', 'description': '', 'some': 'extra'}, ...]

如何选择帖子列以仅包含某些字段?比如:

id| posts
--------
1 | [{'title':'', 'description': ''}, ...]
2 | [{'title':'', 'description': ''}, ...]

有什么想法吗?

PS:postgres的版本是最新的12、13、14...

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: sql postgresql jsonb


【解决方案1】:

您可以考虑使用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":""}]

View on DB Fiddle

或更短

查询 #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":""}]

View on DB Fiddle

查询 #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;

View on DB Fiddle

让我知道这是否适合你。

【讨论】:

  • 非常感谢!这正是我正在寻找的!
  • @RomanZaycev 太好了!还请将此答案标记为已接受的答案,以便帮助其他 Stackoverflow 用户确定他们可能遇到的类似问题的答案。
  • 是的。忘了做。再次感谢您!
猜你喜欢
  • 2017-09-11
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
相关资源
最近更新 更多