智能用户排名计算

时间:2012-12-18 07:35:13

标签: mysql sql ranking

我有一个纸牌游戏,用户根据赢得的游戏数量进行排名。总体评级是预先计算的,以便能够快速加载,但我有关于排名计算的问题。

排名计算如下:

SET @userRank = 0;

UPDATE t_ratings AS r
JOIN
  (
    SELECT
        userId, (@userRank := @userRank + 1) as rank
        FROM (
        SELECT
            r.userId,
            r.solvedCount,
            r.playedCount
       FROM
        t_ratings AS r                        
    ORDER BY r.solvedCount DESC , r.playedCount ASC) AS t
  ) AS rt
  ON rt.userId = r.userId
SET r.rank = rt.rank

但是最近我有时会遇到以下错误:

Deadlock found when trying to get lock; try restarting transaction

因此,我想知道是否有更好的方法来计算用户排名以避免死锁?

1 个答案:

答案 0 :(得分:1)

这就是我在SQL Server中的做法...不确定mySQL是否有窗口函数,因为我不是mySQL人。

With    cte As
(
        Select  Rank() Over (ORDER BY r.solvedCount DESC , r.playedCount ASC) As [rank], 
                userID
        From    t_ratings As r
)
Update  tr
Set     [rank] = c.[rank]
From    t_ratings tr
Join    cte c
        On  tr.userID = c.userID