7

I need to make a query that creates 3 columns that come from 2 tables which have the following relations:

TABLE 1 has Column ID that relates to TABLE 2 with column ID2

In TABLE 1 there is a column called user In TABLE 2 there is a column called names

There can be 1 unique user but there can be many names associated to that user.

If i do the following i get all data BUT the user column repeats itself for each name it has associated. What i want is for use to appear unique but the names columns appear with all the names associated to the user column but separated by commas, like the following:

select user,names from TABLE1 left join TABLE2 on TABLE1.id = TABLE2.id

This will show the users repeated everytime a name appears for that user. what i want is to appear like this:

USER - NAMES
cyrex - pedrox, rambo, zelda
homeboy - carmen, carlos, tom, sandra
jerry - seinfeld, christine
ninja - soloboy

etc....

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Luis Alvarado
  • 8,837
  • 12
  • 46
  • 60

1 Answers1

17

What you are looking for is the GROUP_CONCAT operator.

select user, GROUP_CONCAT(names SEPARATOR ',')
from TABLE1 left join TABLE2 on TABLE1.id = TABLE2.id
group by user
Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177