user1394925
user1394925

Reputation: 752

How to merge db rows together?

I have a query below which displays these results:

SELECT q.QuestionId, q.QuestionContent, an.Answer
FROM Answer an
INNER JOIN Question q ON q.AnswerId = an.AnswerId;

Result of query:

QuestionId     QuestionContent           Answer
1              Who are me and you         B
1              Who are me and you         D
2              Name these Cars            A
2              Name these Cars            B
2              Name these Cars            E
3              What is 2+2                B

What I want to do is merge the answers together for the same QuestionId so the result looks like this below:

QuestionId     QuestionContent           Answer
1              Who are me and you         B D
2              Name these Cars            A B E
3              What is 2+2                B

Is this possible?

Thanks

Upvotes: 0

Views: 68

Answers (1)

JHS
JHS

Reputation: 7871

Try this -

SELECT q.QuestionId,
       q.QuestionContent,
       GROUP_CONCAT(an.Answer, SEPARATOR ' ')
FROM Answer an
INNER JOIN Question q ON q.AnswerId = an.AnswerId
GROUP BY q.QuestionId,
       q.QuestionContent 

Upvotes: 1

Related Questions