3

Below follow my scenario:

CREATE TABLE `CustomerOrder` (
  `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
  `data` json DEFAULT NULL,
  PRIMARY KEY (`id`)
);

And we can use this Customer Order json as example:

{ 
    "creation": "2015-07-30 14:27:51",
    "customer": {
        "id": 2,
        "email": "[email protected]"
    },
    "item": [
        {
            "sku": 182,
            "unitPrice": 0.89,
            "qty": 10
        }, {
            "sku": 712,
            "unitPrice": 12.99,
            "qty": 2
        }
    ]
}

Runing on MySQL console this SQL:

SELECT json_extract(data, '$.item[*].unitPrice') AS price FROM CustomerOrder;

I will have this output:

[ 0.89, 12.99 ]

Now how can I evaluate a SUM of [0.89 + 12.99] or 1..N elements of items?

For my tests I used this version of MySQL Labs:

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/

7 Answers 7

6

I tried to use @Rick's answer but it didn't work for me. So I digged mysql documentation for mysql functions. Here's the working function for 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

Then use the function as @Rick wrote:

select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );
1
  • I can confirm this works in MariaDB 10.3.9 as well
    – Karol S
    Feb 27, 2021 at 0:30
5

Use JSON_TABLE see example:

SET @datax = '[
  { "product":"apple",  "price": 5}, 
  { "product":"banana",  "price": 7}
]';


SELECT price.* 
FROM 
     JSON_TABLE(@datax, '$[*]' COLUMNS (
                price INTEGER PATH '$.price')
     ) price;`

Then, add up the price.

0
2

The following stored function does the trick for me:

delimiter $$
create function sum_array_cells( input_array json )
returns double
language sql deterministic contains sql
begin
    declare array_length integer;
    declare retval double;
    declare cell_value double;
    declare idx int;

    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$$

Then you would invoke that function in a query like this

select sum_array_cells( '[ 0.89, 12.99, 5.23, 2.04 ]' );

Hope this helps, -Rick

1
  • I was not able to create function with the code you gave and it didn't work even after I made it work. Heres the fixed version of your code: Jul 25, 2017 at 7:59
1

MySQL doesn't yet support table functions (hopefully soon!), so we don't have a handy JSON function to produce rows from JSON array. For now, Victor Smt's suggestion using a stored procedure would be my preference, too.

DagW

1
  • 1
    Hi Dag, thanks for yor reply - I find another solution, it's not an elegant solution but are working for now: stackoverflow.com/questions/21567706/… I need to convert the array (using REPLACE) as XML Schema and SUM their nodes. To be honest, it's a very ugly solution, but it's working
    – Ragen Dazs
    Jul 30, 2015 at 19:51
1

Don't know why my code example was truncated. Here's the rest of the function:



    select json_extract( input_array, concat( '$[', idx, ']' ) )
    into cell_value;

    set retval = retval + cell_value;
    set idx = idx + 1;
  end while;

  return retval;

end$$

1
  • May be a bit late, but I helped you fix the code sample. You didn't need to wrap your code in tags. This pieces may now be deleted.
    – Sheepy
    Aug 7, 2021 at 3:03
1

An optmised and updated version of Rick's answer. Tested on MySQL 5.7, MySQL 8.0, and MariaDB 10.3.

Note that it uses decimal for accuracy. Feel free to change it to double or int.

CREATE FUNCTION zy_json_sum ( js_array json )
RETURNS decimal(18,2) DETERMINISTIC
BEGIN
    DECLARE total decimal(18,2) DEFAULT 0.0;
    DECLARE idx int DEFAULT 0;
    SELECT json_length( js_array ) INTO idx;
    WHILE idx > 0 DO
        SET idx = idx - 1;
        SELECT json_extract( js_array, concat( '$[', idx, ']' ) ) + total INTO total;
    END WHILE;
    RETURN total;
END

Usage:

SELECT zy_json_sum( '[1.1, 2.2, "3.3 foo", null, -4.4]' )
-- Output: 2.20
0

Try this :

SELECT (json_extract(data, '$.item[0].unitPrice') + json_extract(data, '$.item[1].unitPrice')) AS price  FROM CustomerOrder
7
  • And how can I do this iteration for all elements from database?
    – Ragen Dazs
    Jul 30, 2015 at 18:40
  • what does it give you when you try this query?
    – ted
    Jul 30, 2015 at 18:43
  • NULL, but $.item[0].unitPrice + $.item[1].unitPrice result 13,88. But I need a iteration SUM, because each order can have N elemts. How can I SUM an customer order with 1000 itens?
    – Ragen Dazs
    Jul 30, 2015 at 18:49
  • just edited my answer if someone reads it later. Still thinking about your issue
    – ted
    Jul 30, 2015 at 18:53
  • you could try and write a procedure creating a temporary table for each client with the prices of items, using a for loop. Take a look here for those procedures : stackoverflow.com/questions/5125096/for-loop-example-in-mysql
    – ted
    Jul 30, 2015 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.