MySQL限制用于计算SUM的行数

时间:2019-04-16 10:52:41

标签: mysql inner-join limit

我正在做一个游戏,每小时计算玩家的得分。需要分数,以便排行榜可以显示排名最高的球员。游戏中赢得的“点数”将为玩家存储在boards_played表中。玩家表中有一个得分字段,该得分每小时用以下SQL更新:

update players p 
       inner join (
          SELECT player_id, sum(points) as total 
            from boards_played
           where time_played > DATE_SUB(now(), INTERVAL 7 DAY)
           GROUP BY player_id) s on p.player_id = s.player_id
  set p.score = s.total

问题在于,从100场比赛中总共赢得50分的人应该比在200场比赛中获得60分的人更好。

简而言之,分数仅应基于最近7天内的最近100场比赛。

1 个答案:

答案 0 :(得分:1)

您可能需要在此处关联一个子查询,以便为每个玩家检索正确的值。

要找到某个玩家的总得分,请使用此子查询。

          SELECT SUM(points) as total
            FROM (
                   SELECT player_id, points
                     FROM boards_played
                    WHERE time_played > DATE_SUB(NOW(), INTERVAL 7 DAY)
                     AND player_id = ***something*** 
                    ORDER BY time_played DESC
                    LIMIT 100
                 ) a

现在,您需要将其合并到外部查询中

UPDATE players p
   SET score =
       (
          SELECT SUM(points) as total
            FROM (
                   SELECT points
                     FROM boards_played
                    WHERE time_played > DATE_SUB(NOW(), INTERVAL 7 DAY)
                      AND points.player_id = p.player_id 
                    ORDER BY time_played DESC
                    LIMIT 100
                 ) a
       )

为什么将其称为相关?子查询中的行points.player_id = p.player_id 将其与外部查询相关。这样可以将LIMIT分别应用于每个玩家的得分。

但是,您最好制作一个可以即时计算此值的视图,而不是更新表。然后,您不必担心一直在更新表。看起来像这样(未调试)。

CREATE VIEW players_with_score AS
SELECT p.player_id, p.col1, p.col2, p.col3,
       (  
          SELECT SUM(points) as total
            FROM (
                   SELECT points
                     FROM boards_played
                    WHERE time_played > DATE_SUB(NOW(), INTERVAL 7 DAY)
                      AND points.player_id = p.player_id 
                    ORDER BY time_played DESC
                    LIMIT 100
                 ) a
       ) score
  FROM player p 

然后您可以说类似的话

  SELECT player_id, score
    FROM players_with_score
   WHERE score > 250