【问题标题】:How to get many values from a single JSON column in PostgreSQL?如何从 PostgreSQL 中的单个 JSON 列中获取多个值?
【发布时间】:2021-06-23 06:13:53
【问题描述】:

在我的数据库中,我目前有一个这样的表:

order_id country data
1 Germany {"selectedProducts": [{"product": {"size": 2.5, "id": 72}, "quantity": 1},{"product": {"size": 3, "id": 25}, "quantity": 1}]}
2 Germany {"selectedProducts": [{"product": {"size": 4, "id": 72}, "quantity": 1},{"product": {"size": 3, "id": 36}, "quantity": 1}]}
3 Italy {"selectedProducts": [{"product": {"size": 2.5, "id": 72}, "quantity": 1}]}

我一直在尝试提出一个 SELECT sql 查询,它可以让我获取产品的 id 以便能够按国家/地区等研究其受欢迎程度,但我没有这样做根本没有成功。

data 列也可以包含不确定数量的产品。 愿意帮忙吗?我已经尝试在 PostgreSQL 中使用 -> 和 ->> 运算符但无济于事,但可能是我没有正确使用它们

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    您应该使用json_array_elements 来提取所有 json 数组元素。示例:

    SELECT
      id, country, json_array_elements(inventory->'selectedProducts')
    FROM 
      products
    

    尝试:db<>fidle

    之后剩下的就是产品,可以使用 -> 或 ->> 运算符通过名称提取单个属性,或使用 json_each 提取所有键值对。

    【讨论】:

    • 非常感谢,终于可以继续这个数据库的分析了:D
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 2021-06-10
    • 2023-03-31
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多