获得用户在排行榜中的位置?

时间:2013-01-01 13:05:38

标签: php mysql sql

我正在制作这个游戏排行榜,我正试图在这个排行榜中获得特定用户的位置。我试过这个但没有运气:

SELECT SUM(points) as points 
FROM publicpoints 
GROUP BY fk_player_id 
WHERE points > (SELECT SUM(points) as points 
                FROM publicpoints 
                WHERE fk_player_id = $playerid)

我应该怎么做?

----------------编辑-----------------

我也尝试过这样,但仍然没有运气,但也许这就是我努力实现的目标:

$sql = mysql_query("SELECT SUM(points) mypoints FROM ".$prefix."_publicpoints WHERE fk_player_id=$playerid");
$row = mysql_fetch_assoc($sql);

$mypoints = $row['mypoints'];

$sql = mysql_query("SELECT SUM(points) as points FROM ".$prefix."_publicpoints 
                        WHERE points < $mypoints
                    GROUP BY fk_player_id");
$row = mysql_fetch_assoc($sql);

$rank = mysql_num_rows($sql);

if(!empty($mypoints)){
    $rank = $row['rank']+1;
} else {
    $rank = 0;
}

1 个答案:

答案 0 :(得分:4)

WHERE子句必须在GROUP BY子句之前,如下所示:

SELECT 
  SUM(points) as points 
FROM publicpoints 
WHERE fk_player_id = $playerid
GROUP BY fk_player_id;

然后,您可以将ORDER BYLIMIT一起使用,以获得具体的Points职位:

SELECT 
  SUM(points) as points 
FROM publicpoints 
WHERE fk_player_id = $playerid
GROUP BY fk_player_id
ORDER BY points
LIMIT 1 -- for top 1;

更新:要获得积分高于当前用户的用户数,可以执行以下操作:

SELECT COUNT(*) AS NumberOfPlayers
FROM
(
    SELECT 
       fk_player_id
    FROM points 
    GROUP BY fk_player_id
    HAVING SUM(points) > (SELECT SUM(points)
                          FROM points 
                          WHERE fk_player_id = 5)
) t;

如果你想让那些积分高于当前用户的玩家,你可以这样做:

SELECT 
   fk_player_id
FROM points 
GROUP BY fk_player_id
HAVING SUM(points) > (SELECT SUM(points)
                      FROM points 
                      WHERE fk_player_id = 5);

Updated SQL Fiddle Demo