【问题标题】:How to query a nested json with varying key value pairs如何查询具有不同键值对的嵌套 json
【发布时间】:2021-08-14 23:54:15
【问题描述】:

我之前的问题已经得到解答,感谢@Erwin Brandstetter 的帮助:

Query individual values in a nested json record

我有后续:

Aurora Postgres - PostgreSQL 13.1。我的jsonb 列值如下所示:

'{
    "usertype": [
        {
            "type": "staff",
            "status": "active",
            "permissions": {
                "1": "add user",
                "2": "add account"
            }
        },
        {
            "type": "customer",
            "status": "suspended",
            "permissions": {
                "1": "add",
                "2": "edit",
                "3": "view",
                "4": "all"
            }
        }
    ]
}'

我想生成一个表格样式的输出,其中每个权限项都显示为一列。如果不为空,则应显示该值,否则为空。

 type     | status    | perm1   | perm2      | perm3 | perm4 | perm5 | perm6
----------+-----------+---------+------------+-------+-------+-------+-------
 staff    | active    | adduser | addaccount | null  | null  | null  | null
 customer | suspended | add     | edit       | view  | all   | null  | null

换句话说,我想要一种方法来找出最大权限计数并在选择查询中显示那么多列。

【问题讨论】:

  • 请让这个问题的读者更容易理解,并在 this 问题中也包含一个minimal reproducible example,即使您的上一个问题已经有一个。
  • 粘性位说了什么。另外,您仍然没有声明您的 Postgres 版本。
  • 用版本和示例详细信息更新了原始问题

标签: sql json postgresql


【解决方案1】:

SQL 查询必须返回固定 列数。返回类型必须在调用时(最迟)知道。到那时,返回的行中列的数量、名称和数据类型是固定的。没有办法在 SQL 中获得真正动态的结果列数。您必须使用两个步骤(到数据库服务器的两次往返):

  1. 确定列表或结果列。
  2. 发送查询以生成该结果。

值得注意的是,这为并发写入负载下的竞争条件留下了时间窗口。

通常,只为可变数量的值返回数组或列表或文档类型(如 JSON)会更简单。或一组行。

如果可能值的最大值较低,例如 6,就像在您添加的示例中一样,则只是过度配置:

SELECT id
     , js_line_item ->> 'type'   AS type
     , js_line_item ->> 'status' AS status
     , js_line_item #>> '{permissions, 1}' AS perm1
     , js_line_item #>> '{permissions, 2}' AS perm2
--   ,  ...
     , js_line_item #>> '{permissions, 6}' AS perm6
FROM   newtable n
LEFT   JOIN LATERAL jsonb_array_elements(n.column1 -> 'usertype') AS js_line_item ON true;

LEFT JOIN 保留没有任何权限的行。

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 2017-12-21
    • 2013-07-07
    • 2019-11-23
    • 2023-03-02
    • 1970-01-01
    • 2022-01-13
    • 2020-07-17
    相关资源
    最近更新 更多