Mysql JOIN计数

时间:2010-03-31 14:30:02

标签: mysql join inner-join

我有2个mysql表:

Question with the following columns : id, question, nranswers

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

另一张表是

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

现在问题是我想得到一个问题的每个答案的回复(id 22)。

P.S。如果nranswers为3,结果应如下所示:

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

1 - 2

2 - 8

3 - 7

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

1 - 3

2 - 8

3 - 14

4 - 19

5 - 8

请帮我解决问题,因为他没有计算未被选中的答案,只计算至少选过一次的答案。

2 个答案:

答案 0 :(得分:3)

我冒昧地添加了用于将每个答案加入问题的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

答案 1 :(得分:0)

考虑this question的一个答案,看起来你需要某种临时表来选择MySQL中的一系列数字。看起来this answer可以很好地扩展。

假设您的问题最多有10个答案。然后你可以这样做:

SELECT Choices.num,IF(Answers.answer IS NULL,0,COUNT(*))
FROM 
    (SELECT choice.num,Question.*
        FROM
           (SELECT 1 num
            UNION ALL
            SELECT 2 num
            UNION ALL
            SELECT 3 num
            UNION ALL
            SELECT 4 num
            UNION ALL
            SELECT 5 num
            UNION ALL
            SELECT 6 num
            UNION ALL
            SELECT 7 num
            UNION ALL
            SELECT 8 num
            UNION ALL
            SELECT 9 num
            UNION ALL
            SELECT 10 num) choice,
           Question
         WHERE Question.id=22
    ) Choices
    LEFT OUTER JOIN Answers 
       ON Answers.question_id=Choices.id AND Answers.answer=Choices.num
   WHERE Choices.num<=Choices.nranswers
   GROUP BY Choices.num;

它很乱,但它有效。如果您需要更多选择,您可以执行类似于上述答案中所做的操作。另外,将WHERE Question.id=22更改为您需要的ID。不需要进行任何其他改变。