0
SELECT DISTINCT q.QuestionContent, o.OptionType, q.NoofAnswers, GROUP_CONCAT(DISTINCT Answer ORDER BY 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 

我上面的查询显示了一组空的结果,即使它应该显示一些结果。假设显示每个不同的问题(我的意思是它应该清楚地显示行,以便没有重复的行在所有列中包含完全相同的数据)任何人都可以修复查询以便输出它应该的结果输出?以下是表格:

会话表:

SessionId  SessonName
3          ANDES

问题表:

QuestionId  SessionId   QuestionNo  QuestionContent       NoofAnswers   ReplyId     QuestionMarks   OptionId
1           3           1           What is 2+2?          1                 1           5               2
2           3           2           What is 2+2?          1                 1           5               2
3           3           3           Name these 2 flowers  2                 2           5               4

答案表:

AnswerId (Auto)  QuestionId  Answer
1                1           A
2                1           B
3                2           A
4                2           D
5                3           C

回复表:

ReplyId  ReplyType
1        Single
2        Multiple

选项表:

OptionId OptionType
1        A-C
2        A-D
3        A-E
4        A-F
4

1 回答 1

1

我稍微改变了你的查询,我得到了结果。首先,我改为使用 a LEFT JOIN,然后如果在附加表中没有答案等,您将收到问题返回。其次,由于您使用的是聚合函数GROUP_CONCAT(),因此需要使用GROUP BY

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

请参阅带有演示的 SQL Fiddle

这将返回结果:

|      QUESTIONCONTENT | OPTIONTYPE | NOOFANSWERS | ANSWER | REPLYTYPE | QUESTIONMARKS |
----------------------------------------------------------------------------------------
| Name these 2 flowers |        A-F |           2 |      C |  Multiple |             5 |
|         What is 2+2? |        A-D |           1 |    ABD |    Single |             5 |
于 2013-01-07T14:53:29.653 回答