我有2个mysql表:

Question with the following columns : id, question, nranswers


Nranswers必须是1到5之间的数字

另一张桌子是

Answers with the following columns: questionid, userid, answer .


现在的问题是我想获得一个问题的每个答案的答复(假设ID为22)。

附言如果nranswers为3,则结果应如下所示:

(正确的号码表示选择了回复号码的次数)

1-2

2-8

3-7

如果nranswers为5,则结果应如下所示:

1-3

2-8

3-14

4-19

5-8

请帮我解决这个问题,atm他不会计算未选择的答案,只会计算至少一次被选择的答案。

最佳答案

我随意添加了question_id列,该列将用于将每个答案与一个问题结合在一起。

Question with the following columns : id, question, nranswers
Answers with the following columns: question_id, userid, answer


这是您的查询:

SELECT answer, COUNT(*) AS answer_count
FROM Answers
GROUP BY answer
WHERE question_id = 22
ORDER by answer


但是,如果nranswers为3,但没有人选择3作为答案,则不会显示。该查询仅显示选择的答案。

编辑:

要获得所有可用答案的计数,而不仅仅是选定的答案,最简单的方法(明智的查询)是摆脱Question.nranswers列并添加表QuestionAnswers:

QuestionAnswers with the following columns: question_id, answer


QuestionAnswers中的数据如下所示:

quesiton_id answer
-------------------
22          1
22          2
22          3


因此,您将为每个问题列出所有可能的答案。

查询将是这样的:

SELECT qa.answer, COUNT(a.question_id) AS answer_count
FROM QuestionAnswers qa
LEFT OUTER JOIN Answers a
  ON qa.question_id = a.question_id AND a.answer = qa.answer
GROUP BY qa.answer
WHERE qa.question_id = 22
ORDER by qa.answer

07-26 05:06