【问题标题】:Creating table views with columns from nested value of a jsonb column使用来自 jsonb 列的嵌套值的列创建表视图
【发布时间】:2021-07-28 10:17:09
【问题描述】:

我在具有以下结构的表之一中有一个 jsonb 列:

{
  "3424": {
    "status": "pending",
    "remarks": "sample here"
  },
  "6436": {
    "status": "new",
    "remarks": "sample here"
  },,
  "9768": {
    "status": "cancelled",
    "remarks": null,
    "by": "customer"
  }
}

我正在尝试创建一个视图,将状态放在各个列中,键是它们的值:

pending | new  | cancelled | accepted | id | transaction
3424    | 6436 | 9768      | null     | 1  | testing

问题是密钥是动态的(数字并对应于某个 id),所以我无法确定使用此处所述功能/操作的确切密钥:https://www.postgresql.org/docs/9.5/functions-json.html

我已经阅读了json_path_query 并且能够在不需要知道密钥的情况下提取这里的状态,但我还不能将它与整数密钥结合起来。

select mt.id, mt.transaction, hstatus from mytable mt
cross join lateral jsonb_path_query(mt.hist, '$.**.status') hstatus
where mt.id = <id>

但这现在将状态返回为行。我对 (postgre)sql 很陌生,所以我只到了这一步。

【问题讨论】:

  • 如果您有两个带有pending 的条目怎么办?还是三个cancelled

标签: postgresql jsonb


【解决方案1】:

您确实可以使用 PATH 查询。不幸的是,在 Postgres 中无法访问 jsonpath 中的“父级”。但是您可以通过将整个值扩展为键/值列表来解决此问题,以便您拥有的 id 值可以通过.key 访问

select jsonb_path_query_first(the_column, '$.keyvalue() ? (@.value.status == "pending").key') #>> '{}' as pending,
       jsonb_path_query_first(the_column, '$.keyvalue() ? (@.value.status == "new").key') #>> '{}' as new,
       jsonb_path_query_first(the_column, '$.keyvalue() ? (@.value.status == "cancelled").key') #>> '{}' as cancelled,
       jsonb_path_query_first(the_column, '$.keyvalue() ? (@.value.status == "accepted").key') #>> '{}' as accepted,
       id, 
       "transaction"
from the_table

jsonpath 函数$.keyvalue() 返回如下内容:

{"id": 0, "key": "3424", "value": {"status": "pending", "remarks": "sample here"}}

这随后用于通过@.value.status 上的条件选择一个元素,然后访问器.key 返回相应的键值(例如3424)

#&gt;&gt; '{}' 是一种将返回的jsonb 值转换为正确的text 值的技巧(否则结果将是例如"3424" 而不仅仅是3424

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2019-09-04
    相关资源
    最近更新 更多