Table 1 – users
------------
id | name
------------
1 | foobar
2 | barfoo
Table 2 – locations
-------------
id | loc_name
-------------
1 | Location1
2 | Location2
3 | Location3
4 | Location4
Table 3 – users_location
-----------------
user_id | loc_id
-----------------
1 | 3
1 | 4
2 | 1
2 | 2
The output that I'm looking for is this one
-------------------------------
name | loc_name
-------------------------------
foobar | Location3,Location4
barfoo | Location1,Location2
Currently here is the code I got
SELECT users.name,locations.loc_name
FROM users
JOIN users_location ON users_location.user_id = users.id
JOIN locations ON locations.id = users_location.loc_id
Here is my current output:
----------------------
name | loc_name
----------------------
foobar | Location3
foobar | Location4
barfoo | Location1
barfoo | Location2
Best Answer
You can use
GROUP_CONCAT
to get your expected result:Also you can use table alias
users AS US
, for better readability.As per the comments, for any separator other than comma, you may use
[SEPARATOR str_val]
alsoORDER BY
will ensure the expected output in the ascending or descending order.Sample code for hyphen as separator: