如何将db行合并在一起?

时间:2012-05-25 21:31:02

标签: mysql sql database

我在下面有一个查询显示这些结果:

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

查询结果:

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

我想要做的是将答案合并为同一个QuestionId,所以结果如下所示:

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

这可能吗?

由于

1 个答案:

答案 0 :(得分:1)

试试这个 -

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