Question

Basically the question is how to get from this:

id    string
1          A
1          B
2          C

to this:

id    string
1          A B
2          C
Was it helpful?

Solution

SELECT id, GROUP_CONCAT(string 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.

OTHER TIPS

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

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.

SELECT id, GROUP_CONCAT(CAST(string as CHAR)) FROM table GROUP BY id

Will give you a comma-delimited string

SET group_concat_max_len=100000000
SELECT id, GROUP_CONCAT(string SEPARATOR ' ') FROM table GROUP BY id;

:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

OR

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;

Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:

SELECT id, GROUP_CONCAT(COALESCE(string,'') SEPARATOR ' ') 
FROM table 
GROUP BY id;

Hope this helps someone else

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top