我有一个表,其中的一个字段有时在 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;
关于mysql - 如何使用 MYSQL 将字段中的值与 JSON 中的数组相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277025/