我有一个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/