json提取物总和返回0而不是正确的值

发布于 2025-02-10 14:05:57 字数 587 浏览 4 评论 0 原文

我正在尝试在MySQL数据库中总结JSON数组的内容,以下是JSON格式和正在运行的查询。有什么问题吗?

//选项json格式:

[
    {
        "optionId": 1,
        "optionName": "With Meat",
        "optionPrice": 2000
    },
    {
        "optionId": 2,
        "optionName": "With Veggies",
        "optionPrice": 0
    }
]

//查询:

SELECT id, SUM(options->'$[*].optionPrice') FROM table_order_items GROUP BY id;

结果为0,当

该查询时应为2000时:

SELECT id, options->'$[*].optionPrice' FROM table_order_items;

正确返回 [2000,0]

I'm trying to sum the contents of a json array in a mysql database, below is the JSON format and the query I'm running. Is there something wrong with it?

// Options JSON Format:

[
    {
        "optionId": 1,
        "optionName": "With Meat",
        "optionPrice": 2000
    },
    {
        "optionId": 2,
        "optionName": "With Veggies",
        "optionPrice": 0
    }
]

// Query:

SELECT id, SUM(options->'$[*].optionPrice') FROM table_order_items GROUP BY id;

The result is 0, when it should be 2000

While this query:

SELECT id, options->'$[*].optionPrice' FROM table_order_items;

correctly returns [2000,0]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲜肉鲜肉永远不皱 2025-02-17 14:05:57

您需要函数代码> 提取价格:

SELECT t.id, 
       SUM(j.price) AS total 
FROM table_order_items t 
JOIN JSON_TABLE(
       t.options,
       '$[*]' COLUMNS(price INT PATH '$.optionPrice')
     ) j
GROUP BY t.id;

请参阅

You need the function JSON_TABLE() to extract the prices:

SELECT t.id, 
       SUM(j.price) AS total 
FROM table_order_items t 
JOIN JSON_TABLE(
       t.options,
       '$[*]' COLUMNS(price INT PATH '$.optionPrice')
     ) j
GROUP BY t.id;

See the demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文