MySQL查询从表中提取两条信息

时间:2014-04-09 19:02:02

标签: mysql sql database

我有一张桌子可以跟踪玩我游戏的人的分数

userID |  game_level |      date_of_attempt        |  score
   1           1          2014-02-07 19:29:00           2
   1           2          2014-02-08 19:00:00           0
   2           1          2014-03-03 11:11:04           4
  ...         ...                 ...                  ...

我正在尝试编写一个查询,对于给定的用户,它会告诉我他们每个game_level的累积分数以及他们在特定{{1}上获得的最后20个分数的平均值(通过排序game_level

例如:

date_of_attempt

是否可以在单个查询中执行此类操作?我经常需要对多个game_levels执行查询,并且我使用一个长子查询来确定需要哪些级别,这使我认为单个查询会更好

1 个答案:

答案 0 :(得分:0)

MySQL不支持分析函数,因此获得平均值比在其他一些RDBMS中更难。在这里,我使用user-defined variables获取分组排名,然后测试结果,仅对20个最新记录进行平均:

SELECT   userID, game_level, SUM(score), x.avg
FROM     my_table JOIN (
           SELECT   AVG(CASE WHEN (@rank := (CASE
                      WHEN t.userID     = @userID
                       AND t.game_level = @gamelevel
                      THEN @rank + 1
                      ELSE 0
                    END) < 20 THEN score END)   AS avg,
                    @userID     := userID     AS userID,
                    @game_level := game_level AS game_level
           FROM     my_table,
                    (SELECT @rank := @userID := @game_level := NULL) init
           ORDER BY userID, game_level, date_of_attempt DESC
         ) x USING (userID, game_level)
GROUP BY userID, game_level

有关详细信息,请参阅How to select the first/least/max row per group in SQL