mysql - 如何查询mysql json列中的对象的对象

标签 mysql mysql-8.0 mysql-json

我有一个order_summary我的 orders 中的 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 的售出商品总数,所以我想获取 quantity 的总和products 内的字段对象。

问题

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

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

我认为这是因为产品数组中存在键。那么我该如何解决这个问题呢?

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

最佳答案

经过一番尝试和错误,在 friend 的帮助下,我找到了以下解决方案,

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

关于mysql - 如何查询mysql json列中的对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58503001/

相关文章:

php - 如果提交另一个表单,为什么 php 在一个表单中输入空白值或重复值

java - 将 MySql 输入流转换为 byte[]

java - 如何修复 "org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL8Dialect]"?

mysql - 如何从 MySQL 中的数字键嵌套 JSON 字段中提取值

MySQL 5.7.12 导入无法从 CHARACTER SET 'binary' 的字符串创建 JSON 值

html - 我可以通过 HTML 表单将 MYSQL 函数作为值传递吗?

mysql - 数据库名称作为 MySQL 查询中的变量

mysql - 如何永久禁用 MySQL 8 中的列统计信息?

mysql - MAX() 和 GROUP BY,需要整个结果的 COUNT(*)

mysql - mysql 5.7中JSON数据类型列中的嵌套更新查询