-1

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

5

1 Answer 1

2

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:

SELECT country.name as country, JSON_ARRAYAGG(user.name) AS userFromCountry
FROM `country`
JOIN `user` ON user.country_id=country.ID
GROUP BY country.name;
  

Try the SQL code here

Sign up to request clarification or add additional context in comments.

3 Comments

Does it handle the conversion to php array? If not, only needs to add $var = json_decode($query['users], true)
Is this a new insight on Stack Overflow or is this possibly a duplicate question?
thanks, it worked. It was not working before because of my apache/mysql version. But now it is working. Sorry for my delay, i lost my computers the last days. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.