2012-04-17 197 views
0

我最近創建了一個評分系統,用戶按照他們的積分降序排列。首先,我曾經在自己的專欄中存儲排名。我用來運行這個循環更新排名:SQL查詢構建

$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'; 

但是,這只是一個選擇語句。無論如何,我可以解決它並改變它,以便它像循環一樣更新表格?

回答

1

請嘗試使用下面的查詢:

set @rownum:=0; 
update sector0_players set [email protected]:[email protected]+1 ORDER BY points DESC; 

PHP代碼就可以了,

mysql_query("set @rownum:=0;"); 
mysql_query("update sector0_players set [email protected]:[email protected]+1 ORDER BY points DESC;"); 
+0

set @rownum:= 0;#MySQL返回一個空的結果集(即零行)。 update sector0_players set scoreboard_rank = @ rownum:= @ rownum + 1 ORDER BY points DESC;#MySQL返回一個空結果集(即零行)。<---這是我不斷收到的錯誤... – 2012-04-17 06:23:44

+0

如果你再次運行查詢,它會顯示該消息。嘗試將記分板等級更新爲零,然後運行一次查詢。 – Prabhuram 2012-04-17 06:31:34

+0

這工作完美!你能解釋一下爲什麼這個級別因爲這個查詢而調整。我需要能夠在將來修改它。 :) *編輯*有沒有辦法從PHP執行這個權利? – 2012-04-17 06:42:40

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 
)