【问题标题】:How to query an object of objects in mysql json column如何在mysql json列中查询对象的对象
【发布时间】:2019-10-22 11:12:57
【问题描述】:

我的orders 表中有一个order_summary JSON 列,其结构如下

{
  "total": 16.895,
  "products": { // products is an object of objects instead of array of objects
    "98": {
      "price": "2.400",
      "quantity": 2,
      "sub_total": 4.8,
      "product_id": 100,
      "variant_id": 98
    },
    "395": {
      "price": "3.900",
      "quantity": 1,
      "sub_total": 3.9,
      "product_id": 401,
      "variant_id": 395
    },
    "732": {
      "price": "7.695",
      "quantity": 1,
      "sub_total": 7.695,
      "product_id": 754,
      "variant_id": 732
    }
  }
}

我要做什么,

我必须计算给定variant_id 的总销售量,所以我想获取products 对象内的quantity 字段的总和。

问题

遗憾的是 products 字段不是对象数组,而是对象的对象。键是variant_id 本身。所以我的以下查询不起作用

SELECT sum(order_summary->"$.products.quantity") FROM orders where order_summary->"$.products.variant_id" = 98(返回空结果集)

我认为这是因为 products 数组中存在键。那么我该如何解决呢?

我正在使用 Mysql 8,如果需要更多信息,请告诉我。

【问题讨论】:

    标签: mysql mysql-8.0 mysql-json


    【解决方案1】:

    经过反复试验,在朋友的帮助下,我找到了以下解决方案,

    SELECT SUM(order_summary -> '$.products."98".quantity') as sum
    FROM orders
    WHERE JSON_CONTAINS_PATH(order_summary, 'all', '$.products."98"')
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 2014-08-09
      • 2016-12-12
      • 2013-09-13
      • 2019-02-07
      • 2019-04-20
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多