mysql - 如何使用 MYSQL 将字段中的值与 JSON 中的数组相加?

标签 mysql

我有一个表,其中的一个字段有时在 JSON 中有多个数组。

MySQL 8.0.11

动态链接库

CREATE TABLE T
    (`user` varchar(4), `sales` int, `reference` varchar(400) DEFAULT NULL, `quantity` float DEFAULT NULL, `orders` int)
;

数据

INSERT INTO T
    (`user`, `sales`, `reference`, `quantity`, `orders`)
VALUES
    ('xx01', 100, '[{"productid":"80000052","quantity":"1","reference":"ML-41"},{"quantity":1,"reference":"ML-32","productid":"ML-52"},{"productid":"80000052","quantity":3,"reference":"ML-11"}]', 0, 0),
    ('xx02', 200, '[{"productid":"80000052","quantity":2}]', 0, 0),
    ('xx02', 400, '[{"productid":"80000052","quantity":3}]', 0, 0),
    ('xx03', 300, '[{"productid":"80000052","quantity":4}]', 0, 0),
    ('xx03', 500, '[{"productid":"80000052","quantity":5}]', 0, 0)
;

以下查询使用“reference”字段 JSON 数组中的“quantity”值更新字段“quantity”:

UPDATE T t2, 
( SELECT sales, quant FROM T, JSON_TABLE(T.reference,
    "$[*]" COLUMNS(
        quant VARCHAR(400) PATH "$.quantity"
        )
    ) AS jt1
) t1
SET t2.quantity = t1.quant
WHERE t1.sales = t2.sales;

查询采用第一行第一个数组中的“数量”,并忽略该行“引用”字段中的以下 2 个数组。

有没有办法将第一行“引用”字段的所有 3 个数组的“数量”相加?

最佳答案

使用 JOIN ... ON 加上 GROUP BY 和 SUM() AS 而不是 WHERE

UPDATE T t2
  JOIN (SELECT sales, SUM(quant) AS qu FROM T, JSON_TABLE(T.reference,
            "$[*]" COLUMNS(
                quant VARCHAR(400) PATH "$.quantity"
                )
            ) AS jt1
        GROUP BY sales) t1
  ON t2.sales = t1.sales
SET t2.quantity = t1.qu;

db-fiddle

关于mysql - 如何使用 MYSQL 将字段中的值与 JSON 中的数组相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277025/

相关文章:

c# - 将表拆分为组 - PHP 和 MYSQL

java - 如何加密mysql中的某些表

java - @使用sql和java

MySQL在按条件按多列分组时选择行

c# - 如何保证门票不会超售?

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - 为什么 PHP 中的查询内部查询比 2 个查询慢?

javascript - jquery ajax 调用 db 无响应

mysql - 无法在Mavericks上启动MySQL

mysql - 创建一个表给我一个无效的语法错误信息