Search code examples
mysqlselectgroup-concat

MySQL Query SELECT multiple rows


I have the following table:

surveys
comp_id    question
4          What is your name?
4          How are you?
4          Where do you live?
5          Who are you?
5          What is your birthday?

I need help writing a Query that gives me the following output:

comp_id    my_questions
4          What is your name?How are you?Where do you live?
5          Who are you?What is your birthday?

Thanks,


Solution

  • You are looking for the GROUP_CONCAT() function. Use it like this:

    SELECT comp_id, GROUP_CONCAT([DISTINCT] question [ORDER BY some_field ASC/DESC] [SEPARATOR '']) as my_questions
    FROM surveys
    GROUP BY comp_id
    

    Note I have shown some some optional values to pass into GROUP_CONCAT in []. To get exact like you are showing just use GROUP_CONCAT(question SEPARATOR ''). The optional items let you look for distinct question values or order them by any field(s) (including question itself).