下面是我的场景:
CREATE TABLE `CustomerOrder` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
`data` json DEFAULT NULL,
PRIMARY KEY (`id`)
);
我们可以使用这个客户订单 json 作为示例:
{
"creation": "2015-07-30 14:27:51",
"customer": {
"id": 2,
"email": "foo@bar.com"
},
"item": [
{
"sku": 182,
"unitPrice": 0.89,
"qty": 10
}, {
"sku": 712,
"unitPrice": 12.99,
"qty": 2
}
]
}
在 MySQL 控制台上运行这条 SQL:
SELECT json_extract(data, '$.item[*].unitPrice') AS price FROM CustomerOrder
;
我会得到这样的输出:
[ 0.89, 12.99 ]
现在如何计算 [0.89 + 12.99] 或 1..N 个项目元素的 SUM?
对于我的测试,我使用了这个版本的 MySQL 实验室:
http://mysqlserverteam.com/json-labs-release-native-json-data-type-and-binary-format/
最佳答案
我尝试使用@Rick 的回答,但它对我不起作用。所以我挖掘了 mysql 函数的 mysql 文档。这是 mysql 5.7.14 的工作函数,
create function sum_array_cells( input_array json )
returns double
BEGIN
DECLARE array_length INTEGER(11);
DECLARE retval DOUBLE(19,2);
DECLARE cell_value DOUBLE(19,2);
DECLARE idx INT(11);
SELECT json_length( input_array ) INTO array_length;
SET retval = 0.0;
SET idx = 0;
WHILE idx < array_length DO
SELECT json_extract( input_array, concat( '$[', idx, ']' ) )
INTO cell_value;
SET retval = retval + cell_value;
SET idx = idx + 1;
END WHILE;
RETURN retval;
END
然后使用@Rick 写的函数:
select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );
关于MySQL 实验室 JSON native 类型 : How SUM the result of an array returned by jsn_extract?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31731513/