MySQL 实验室 JSON native 类型 : How SUM the result of an array returned by jsn_extract?

标签 mysql json nosql mysql-5.7

下面是我的场景:

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://downloads.mysql.com/snapshots/pb/mysql-5.7.7-labs-json/mysql-5.7.7-labs-json-linux-el6-x86_64.tar.gz

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/

相关文章:

mysql - 有计数不起作用

hadoop - 无法在hbase中正确插入列

python - 仅在一台机器上工作的无方案数据库解决方案?

php - CI中如何将多维数组插入数据库?

mysql - 加载 XML 无法识别的语句类型

php - 如何制作可搜索的下拉菜单

SQL Server : Transform arrays of JSON objects into table format

c# - 如何将 JSON 字符串绑定(bind)到真实对象定义?

javascript - jQuery从JSON解析时找不到元素

mysql - MongoDB 重读,相对低写,小操作性能