1

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

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;
}
4

1 回答 1

4

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

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

然后你可以使用ORDER BYwithLIMIT来获得一个特定的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);

更新的 SQL Fiddle 演示

于 2013-01-01T13:06:48.787 回答