Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GROUP BY to concatenate strings in MySQL?

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 
like image 579
Paweł Hajdan Avatar asked Sep 29 '08 17:09

Paweł Hajdan


People also ask

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

How do I concatenate a query in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.


2 Answers

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

https://dev.mysql.com/doc/refman/8.0/en/aggregate-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.

like image 94
Scott Noyes Avatar answered Oct 07 '22 04:10

Scott Noyes


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.

like image 29
Graeme Perrow Avatar answered Oct 07 '22 05:10

Graeme Perrow