Rag*_*azs 2 mysql json nosql mysql-5.7
下面按照我的场景:
CREATE TABLE `CustomerOrder` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
`data` json DEFAULT NULL,
PRIMARY KEY (`id`)
);
Run Code Online (Sandbox Code Playgroud)
我们可以使用这个 Customer Order 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
在 MySQL 控制台上运行此 SQL:
SELECT json_extract(data, '$.item[*].unitPrice') AS price FROM CustomerOrder;
我会有这个输出:
[ 0.89, 12.99 ]
Run Code Online (Sandbox Code Playgroud)
现在我如何评估 [0.89 + 12.99] 或 1..N 个项目元素的总和?
对于我的测试,我使用了这个版本的 MySQL Labs:
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
Run Code Online (Sandbox Code Playgroud)
然后使用@Rick 写道的函数:
select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );
Run Code Online (Sandbox Code Playgroud)
使用 JSON_TABLE 参见示例:
SET @datax = '[
{ "product":"apple", "price": 5},
{ "product":"banana", "price": 7}
]';
SELECT price.*
FROM
JSON_TABLE(@datax, '$[*]' COLUMNS (
price INTEGER PATH '$.price')
) price;`
Run Code Online (Sandbox Code Playgroud)
然后,将价格加起来。
| 归档时间: |
|
| 查看次数: |
5683 次 |
| 最近记录: |