【问题标题】:Extract all values from json in sql table从sql表中的json中提取所有值
【发布时间】:2017-07-10 19:19:00
【问题描述】:

我有一个 postgresql 表,它有一个 json 格式的列。

示例列值:

{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}

现在我想选择这一列,并为每一行中的所有项目提取"price"

查询获取列:

select items from my_table

要提取特定项目的 json 值,我可以使用

select items -> 'Orange' -> 'price' as price
from my_table

但是如何提取所有商品(Apple、Orange)的价格?可能是一个数组。

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    使用json_each(),例如:

    with my_table(items) as (
        values (
        '{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json
        )
    )
    
    select key, (value->>'price')::numeric as price
    from my_table,
    json_each(items)
    
      key   | price 
    --------+-------
     Apple  |   100
     Orange |    80
    (2 rows)    
    

    【讨论】:

    • 如何将此处的硬编码 json 值替换为我实际表中的查询?
    • 跳过with... 并执行select ...
    【解决方案2】:
    t=# with my_table(items) as (
      values('{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json)
    )
    select
      json_object_keys(items)
    , items->json_object_keys(items)->>'price'
    from my_table;
     json_object_keys | ?column?
    ------------------+----------
     Apple            | 100
     Orange           | 80
    (2 rows)
    

    json_object_keys: https://www.postgresql.org/docs/9.5/static/functions-json.html

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2021-02-21
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多