I have a simple database with the user and the country tables.
Which user belongs to only one country.
Which country has a list of users.
Right now Im using group_concat (code below) and its working in a "manual" way where Im suppose to build the array myself in PHP.
That’s my output right now:
country | userFromCountry |
---|---|
Brazil | John / Richard / Robert |
But I wonder if there’s a better way to bring the data as an "automatic" array, something like that
country | userFromCountry |
---|---|
Brazil | [John] [Richard] [Robert] |
I could make it "manually" with concat but when I try with JSON_ARRAY i have a "more than one row returned" error.
Fiddle example:
https://sqlfiddle.com/mysql/online-compiler?id=a2bede84-5293-4366-aa84-ff285322b92a
Thank you
2
Answers
JSON_ARRAYAGG() is available in MySQL 5.7.22 and later.
You just need to use
JSONARRAY_AGG
aggregation function. Also using JOIN the tables is more efficient way to achieve desired result, so I can advise next query:Try the SQL code here