3

我有两张桌子questionsanswered. answered包含所有用户的所有问题的答案。一个用户可以多次回答一个问题。可以正确或错误地回答问题。

我正在寻找一个查询,它将返回一个类别中所有问题的正确和错误答案的计数。不过,我只想使用最新的答案。因此,如果用户之前错误地回答了相同的问题并且最近正确地回答了相同的问题,我只想计算最新的 - 正确的 - 一个。

这是我到目前为止得到的:

http://sqlfiddle.com/#!2/31e2e/2/0

SELECT a.correct, count(*) as count
FROM answered a JOIN questions q ON a.question_id = q.id 
WHERE a.user_id = 1 AND q.category_id = 1
GROUP BY correct

它返回

|  CORRECT  |  COUNT  |
-----------------------
|  0        |   2     |
-----------------------
|  1        |   4     |
-----------------------

我想要的是

|  CORRECT  |  COUNT  |
-----------------------
|  0        |   1     |
-----------------------
|  1        |   2     |
-----------------------
4

2 回答 2

2

这是您需要的查询:

SELECT a.correct, count(*) as counter
FROM answered a
JOIN (SELECT user_id, question_id, max(created) as maxCreated
      FROM answered
      GROUP BY user_id, question_id) aux
  ON a.user_id = aux.user_id AND
     a.question_id = aux.question_id AND
     a.created = aux.maxCreated
JOIN questions q ON a.question_id = q.id
WHERE a.user_id = 1 AND q.category_id = 1
GROUP BY a.correct

使用aux子查询仅选择来自给定用户的问题的最后一个答案的行。

于 2012-07-31T15:37:36.987 回答
1

如果您只需要在给出正确答案时计算正确答案:

select b.correct, count(*) from
(
SELECT a.question_id, max(a.correct) correct 
FROM answered a JOIN questions q ON a.question_id = q.id 
WHERE a.user_id = 1 AND q.category_id = 1
GROUP BY a.question_id
 ) B 
group by b.correct

如果后来不正确的答案消除了正确的答案,并且您只需要最后/当前的结果:

select a.correct,count(*) from 
(
select user_id, question_id, max(created) maxDate 
from answered a WHERE a.user_id = 1
group by a.user_id, a.question_id
) m

join answered a 
 on m.question_id=a.question_id 
    and m.user_id=a.user_id
    and m.maxDate=a.created
join questions q on a.question_id=q.id

where q.category_id = 1

group by a.correct
于 2012-07-31T15:42:10.437 回答