mysql选择并计数,Mysql JOIN计数

I have 2 mysql tables :

Question with the following columns : id, question, nranswers

Nranswers must be a number from 1 to 5

And the other table is

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

Now the problem is that I want to get the replies for each answer for one question(id 22 let's say) .

P.S. If the nranswers is 3, the result should look like this:

(the right number means how many times the reply number was chosen)

1 - 2

2 - 8

3 - 7

If the nranswers is 5, the result should look like this:

1 - 3

2 - 8

3 - 14

4 - 19

5 - 8

Please help me out with the query, atm he's not counting the answers that weren't chosen, only the ones that were chosen at least one time.

解决方案

I took the liberty of adding the question_id column that will be used to join each answer with a question.

Question with the following columns : id, question, nranswers

Answers with the following columns: question_id, userid, answer

Here's your query:

SELECT answer, COUNT(*) AS answer_count

FROM Answers

GROUP BY answer

WHERE question_id = 22

ORDER by answer

However, if nranswers is 3, but nobody picked 3 as their answer, it won't show. This query only shows the answers that were chosen.

Edit:

To get a count of all available answers, not just the selected ones, the simplest way (query wise) would be to get rid of the Question.nranswers column and add the table QuestionAnswers:

QuestionAnswers with the following columns: question_id, answer

The data in QuestionAnswers would like this:

quesiton_id answer

-------------------

22 1

22 2

22 3

So, you'd have all the possible answers listed for each question.

The query would then be this:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值