Search code examples
mysqlgroup-bygroup-concat

MySQL group_concat on groups listings


I have the following table:

id | group_id | str     | position_number
 1 |        1 | first   | 1
 2 |        1 | string  | 2
 3 |        2 | And     | 1
 4 |        2 | another | 2
 5 |        2 | string  | 3

I'm searching for the SQL query which returns the following result:

group_id | str
       1 | firststring
       2 | Andanotherstring

How can I do that with group concat, is it at all possible?


Solution

  • SELECT
    group_id
    , GROUP_CONCAT(str ORDER BY position_number SEPARATOR '')
    FROM
    your_table
    GROUP BY group_id
    

    Not so hard, isn't it?

    It's a good idea to consult the manual for such questions.