我有2个mysql表
1. questions: with the following columns: id, title, answer1, answer2, answer3, answer4, answer5, nranswers.
和
2. answers with the following columns: id, questionid, userid, answer
每个问题最多有5个答案(可以有2到5个答案)。我的问题是我想从我的数据库中选择一个给定的问题,选择每个选项的次数。
例如,假设我的问题是id为46,有4个答案,48个用户投票选择#2,37个用户选择#1,39个选项选择#4。
我想要一个选择它的查询并写下这些东西:
1 37 2 48 3 0 4 39
P.S。很重要!它必须只计算NRANSWERS答案,并且必须回复之前没有投票的事情。
答案 0 :(得分:1)
最佳方法:更改表格defs:
Questions (Question_ID, title)
Answers (Answer_ID, Question_ID, answer_text)
Votes (User_ID, Answer_ID)
其中包含与def相同的数据,但位于first normal form。现在选择计数非常简单
SELECT
a.Answer_ID,
COUNT(v.User_ID)
FROM
Questions q
LEFT JOIN Answers a ON q.Question_ID = a.Question_ID
LEFT JOIN Votes v ON a.Answer_ID = v.Answer_ID
WHERE q.Question_ID = 46 -- or any other question ID
GROUP BY a.Answer_ID
ORDER BY a.Answer_ID;
答案 1 :(得分:0)
选择q.id作为问题,a.answer作为答案,计数(a.answer)作为计数来自问题q,通过q.id回答组,a.answer
上面的问题,它将返回如下
question answer Count
1 1 37
1 2 48
1 4 39
1 3 0 this is missing
OR
选择a.question_id,a.answer,count(a.answer)FROM test.answers a Group by a.question_id,a.answer