Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate function in mariaDB

Tags:

mysql

mariadb

I am new to mariadb, and I was using MySQL to develop something, after switching to mariadb it is not working, the error part I find is located at 'JSON_ARRAYAGG', in previously I was using JSON_ARRAYAGG to combine result as array by Group by as below

SELECT column1, JSON_ARRAYAGG(column2) AS column2 FROM table GROUP BY column1;

Transformation

column1    column2               column1    column2
1            a                      1       ['a','b']
1            b                      2       ['cc','dd']
2            cc          --->       3       ['e']
2            dd
3            e

Is there a way to do so in mariadb? Thank you in advance!

like image 216
MMzztx Avatar asked Nov 29 '22 21:11

MMzztx


2 Answers

Creating an aggregate function in MariaDB v10.3.3 :

DELIMITER //

DROP FUNCTION IF EXISTS JSON_ARRAYAGG//

CREATE AGGREGATE FUNCTION IF NOT EXISTS JSON_ARRAYAGG(next_value TEXT) RETURNS TEXT
BEGIN  

 DECLARE json TEXT DEFAULT '[""]';
 DECLARE CONTINUE HANDLER FOR NOT FOUND RETURN json_remove(json, '$[0]');
      LOOP  
          FETCH GROUP NEXT ROW;
          SET json = json_array_append(json, '$', next_value);
      END LOOP;  

END //
DELIMITER ;

And use it like this:

SELECT column1, JSON_ARRAYAGG(column2) AS column2 FROM table GROUP BY column1;

will work.

like image 105
Pawan Singh Avatar answered Dec 12 '22 01:12

Pawan Singh


You can emulate it by wrapping the GROUP_CONCAT with brackets using CONCAT.

SELECT column1, CONCAT('[', GROUP_CONCAT(column2), ']') AS column2 FROM table GROUP BY column1;
like image 25
markusjm Avatar answered Dec 12 '22 03:12

markusjm