SQL:获取最近的最大条目

时间:2014-02-14 16:10:13

标签: mysql groupwise-maximum

任何人都知道如何从此表中获得最新,最高分:

----------------------------------------
|id |game_id |level |score |date       |
----------------------------------------
|1  |0       |1     |90    |1391989720 |
|1  |0       |1     |95    |1391989721 |
|1  |0       |1     |95    |1391989722 |
|1  |1       |1     |4     |1391989723 |
|1  |1       |1     |8     |1391989724 |
|1  |1       |2     |6     |1391989725 |
----------------------------------------

到目前为止,我有这个:

SELECT progress_max.game_id, 
       progress_max.level, 
       progress_max.date AS max_date,              
       max_score 
FROM 
(
    SELECT game_id, level, MAX(score) AS max_score
    FROM cdu_user_progress 
    WHERE lesson_id = 1 
    GROUP BY game_id, level 
) AS ms 
JOIN cdu_user_progress progress_max ON progress_max.game_id = ms.game_id AND progress_max.level = ms.level AND progress_max.score = ms.max_score 
WHERE progress_max.lesson_id = 1 
GROUP BY game_id, level

但这只能获得FIRST最高分(日期1391989721)......

1 个答案:

答案 0 :(得分:1)

有一个更简单的解决方案,使用order by来获得最佳得分:

select game_id, level, score, date 
from cdu_user_progress
where id = 1
order by score desc, date desc
limit 1

要获得所有最佳成绩和最新时间​​,您需要加入。

select a.game_id, a.level, a.score, max(p.date) 
from (select game_id, level, max(score) as score
from cdu_user_progress
group by game_id, level) as a
inner join cdu_user_progress p
on a.game_id = p.game_id, a.level = p.level, a.score = p.score
group by a.game_id, a.level, a.score

实际上,既然你的问题不够明确,我不确定这是不是你想要的。