0

我最近创建了一个评分系统,其中用户按他们的分数降序排列。首先,我曾经将排名存储在自己的列中。我曾经运行这个循环来更新排名:

$i = 1;
    $numberOfRows = mysql_query('SELECT COUNT(`id`) FROM sector0_players');
    $scoreboardquery = mysql_query("SELECT * FROM sector0_players ORDER BY points DESC");
    while(($row = mysql_fetch_assoc($scoreboardquery)) || $i<=$numberOfRows){
        $scoreid = $row['id'];
        $mysql_qeury = mysql_query("UPDATE sector0_players SET scoreboard_rank = '$i' WHERE id = '$scoreid'");
    $i++;
    }

这真的很难,更不用说在大量用户上实际运行它的速度很慢。相反,我尝试构建一个查询并以这个结束。

SET @rownum := 0;
SELECT scoreboard_rank, id, points
FROM (
SELECT @rownum := @rownum + 1 AS scoreboard_rank, id, points FROM sector0_players ORDER BY points DESC
)
as result WHERE id = '1';

但是,这只是一个选择语句。无论如何我可以绕过它并更改它,以便它像循环一样更新表格?

4

2 回答 2

1

请尝试使用以下查询:

set @rownum:=0;
update sector0_players set scoreboard_rank=@rownum:=@rownum+1 ORDER BY points DESC;

PHP代码可以,

mysql_query("set @rownum:=0;");
mysql_query("update sector0_players set scoreboard_rank=@rownum:=@rownum+1 ORDER BY points DESC;");
于 2012-04-17T06:20:17.217 回答
0

您可以尝试使用 RANK 函数.. 我还没有实际执行 SQL,但它应该可以工作

UPDATE sector0_players
SET scoreboard_rank =
(
SELECT srank
FROM
(
    SELECT id,points, RANK() OVER (ORDER BY points) AS srank
    FROM sector0_players T
) D
WHERE D.id = sector0_players.id
AND  D.points = sector0_players.points
)
于 2012-04-17T06:23:30.833 回答