使用来自 jsonb 列的嵌套值的列创建 table 视图

Creating table views with columns from nested value of a jsonb column

我在其中一个表中有一个 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)所以我无法确定使用此处所述 functions/operations 的确切密钥: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>

但是这 returns 目前状态为行。我对 (postgre)sql 很菜鸟,所以我才走到这一步。

您确实可以使用 PATH 查询。不幸的是,在 Postgres 中无法访问 jsonpath 中的“父级”。但是你可以解决这个问题,通过将整个值扩展到 key/values 的列表,这样你拥有的 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() returns 像这样:

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

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

#>> '{}' 是一种将返回的 jsonb 值转换为适当的 text 值的技巧(否则结果将是 "3424" 而不是 3424.