How to use GROUP BY to concatenate strings in MySQL?

前端 未结 6 591
慢半拍i
慢半拍i 2020-11-22 03:56

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         


        
6条回答
  •  情深已故
    2020-11-22 04:07

    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(name,'') SEPARATOR ' ') 
    FROM table 
    GROUP BY id;
    

    Hope this helps someone else

提交回复
热议问题