2012-07-31 68 views
3

我有兩個表questionsansweredanswered包含所有用戶的所有問題的答案。一位用戶可以多次回答問題。一個問題可以被正確或不正確地回答。MySQL:通過查詢獲取組中的最新值

我在查找一個查詢,它將返回一個類別中所有問題的正確答案和錯誤答案的計數。 儘管我只想使用最新的答案。因此,如果用戶之前正確回答了相同的問題,並且正確地更近一些,我只想計算最新的 - 正確的 - 。

這是我走到這一步:

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

是如何解答確定爲當前或更早?有'datetime'列嗎? – 2012-07-31 15:43:28

+0

是的,看看他發佈的sqlfiddle.com頁面:) – 2012-07-31 15:53:21

回答

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子查詢與最後答案從給定用戶問題只選擇行。

+0

刪除'as'maxCreated''和'as'counter''的引號。 – 2012-07-31 15:49:52

+0

@ypercube完成了,但爲什麼這是一個問題? – 2012-07-31 15:58:26

+0

單引號應該用於字符串文字,而不是列名或別名。這就是雙引號(也是MySQL中的反引號)。 – 2012-07-31 16:07:38

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

該查詢給出了預期的結果,但不正確。您正在選擇具有更正答案的行,而不是最後一個答案的行。 – 2012-07-31 15:47:34

+0

已修復。我認爲只有一個正確的答案需要標記用戶回答的問題。 – valex 2012-07-31 16:37:37