How to use GROUP BY to concatenate strings in MySQL?

Paweł Hajdan picture Paweł Hajdan · Sep 29, 2008 · Viewed 265.8k times · Source

Basically the question is how to get from this:

foo_id   foo_name
1        A
1        B
2        C

to this:

foo_id   foo_name
1        A B
2        C

Answer

Scott Noyes picture Scott Noyes · Sep 29, 2008
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.