MySQL:通过查询获取组中的最新值

时间:2012-07-31 15:24:04

标签: mysql sql database

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

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

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

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     |
-----------------------

2 个答案:

答案 0 :(得分: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子查询仅选择具有给定用户问题的最后答案的行。

答案 1 :(得分: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