Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL how to select into JSON ARRAY

Tags:

in MySQL 5.7 we have the JSON_ARRAY object. I'd like to perform something similar to a SELECT GROUP_CONCAT(field) but with the results into a JSON_ARRAY.

My current query is:

SELECT GROUP_CONCAT(name) FROM users;

result: john,michael,sofia

I'd like the result to be: ["john","michael","sofia"]

My current solution is:

select @j:=json_array_append(@j,'$',name) from users

But that's very inefficient since it's re-calculated for every row. Is it possible to achieve that more efficiently?

like image 995
Stefano Giacone Avatar asked Mar 31 '17 15:03

Stefano Giacone


2 Answers

You can use JSON_ARRAY to achieve what you want :

SELECT JSON_ARRAY(GROUP_CONCAT(name SEPARATOR ',')) AS names FROM users;

Like this it will let you obtain the desired result without having to re-calculate for each row.

like image 130
MI53RE Avatar answered Sep 22 '22 10:09

MI53RE


You can use JSON_ARRAYAGG Example here:

https://github.com/AndreyMashukov/mysql-json-serializer

like image 44
Andrey Mashukov Avatar answered Sep 24 '22 10:09

Andrey Mashukov