GROUP BY子句未正确显示行

时间:2012-10-11 00:47:52

标签: mysql sql database group-by

我在下面有一个“答案”数据库表:

答案表

AnswerId SessionId QuestionId Answer
10       AAD       7          A
11       AAD       7          B
12       AAD       7          D
13       AAA       1          A
14       AAC       1          True

现在您可以看到上面的问题7在考试(会话)AAD中有3个答案,考试(会话)AAA中的问题1有1个答案,这些是考试(会话)中问题1的1个答案AAC

所以当我在php / html中输出表时,它应该显示如下:

  Question  Answer

  7         ABD
  1         A
  1         True

但问题是它在3个单独的行中显示我不想要的表:

Question  Answer
7         ABD
7         ABD
7         ABD
1         ATrue
1         ATrue

所以我猜我的GROUP BY CLAUSE不正确,我的问题是GROUP BY Clause应该是什么才能正确?

 SELECT DISTINCT an.SessionId, an.QuestionId, q.QuestionContent, o.OptionType, q.NoofAnswers, GROUP_CONCAT( an.Answer
ORDER BY an.Answer
SEPARATOR  ' ' ) AS Answer, r.ReplyType, q.QuestionMarks
FROM Answer an
INNER JOIN Question q ON q.QuestionId = an.QuestionId
JOIN Reply r ON q.ReplyId = r.ReplyId
JOIN Option_Table o ON q.OptionId = o.OptionId
GROUP BY an.SessionId, an.QuestionId

下面我已经为“问题”和“答案”表格包含了SHOW CREATE TABLES:

问题表:

 CREATE TABLE `Question` (
     `SessionId` varchar(10) NOT NULL,
     `QuestionId` int(10) NOT NULL,
     `QuestionContent` varchar(5000) NOT NULL,
     `NoofAnswers` int(2) NOT NULL,
     `ReplyId` int(1) NOT NULL,
     `QuestionMarks` int(4) NOT NULL,
     `OptionId` int(2) NOT NULL,
     PRIMARY KEY (`SessionId`,`QuestionId`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

答案表:

CREATE TABLE `Answer` (
 `AnswerId` int(10) NOT NULL AUTO_INCREMENT,
 `SessionId` varchar(10) NOT NULL,
 `QuestionId` int(10) NOT NULL,
 `Answer` varchar(5) NOT NULL,
 PRIMARY KEY (`AnswerId`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8

下面是“问题”表行(我只包括SessionId和QuestionId列,因为它们与这种情况相关:

SessionId QuestionId 
AAA       1
AAC       1
AAD       7

“答案”表格中的行位于此问题的顶部。

更新:通过上面的查询,我得到了这些结果(仅包括相关列):

SessionId  QuestionId  Answer
AAA        1           A A        // This row answer should only be "A"
AAC        1           True True  //This row answer should only be "True"
AAD        7           A B D      //This row is fine

1 个答案:

答案 0 :(得分:1)

您需要添加GROUP BY子句。试试这个,(这是一个简化的版本

SELECT QuestionID, GROUP_CONCAT(Answer SEPARATOR '')
FROM tableName
GROUP BY SessionID, QuestionID

SQLFiddle Demo