我有一个名为Leaderboard的表,有2列,PlayerName和PlayerRating。我希望能够访问特定的PlayerName,获得他们的PlayerRating但是他们的排名(例如:他们是第一,第二,第十?)。我做了一些阅读,我确实找到了一种方法,但我似乎无法将其翻译成PHP并实际打印该值。请记住,我对MySQLi或PHP不是很有经验。
我目前正在通过以下方式获取我的PlayerRating:
$CurrentRating = $Connection->query("SELECT CurrentRating FROM Leaderboard WHERE PlayerName='$PlayerName'")->fetch_assoc()["CurrentRating"];
我可以echo $CurrentRating;
完成工作。现在找到PlayerRank我发现了几个帖子,解释了我的查询应该如何
SET @rank=0; SELECT @rank:=@rank+1 As rank
所以一开始我想是:
query("SET @rank=0; SELECT @rank:=@rank+1 As rank, CurrentRating FROM Leaderboard [...]
但我似乎无法让它正常工作并获得正确打印的等级。我尝试回复$CurrentRating["rank"]
以及以下几种变体:
$CurrentRank = $Connection->query("SET @rank=0; SELECT @rank:=@rank+1 As rank, SELECT CurrentRating FROM Leaderboard WHERE PlayerName='$PlayerName'")->fetch_assoc()["rank"];
有人可以帮我写一下吗? 提前谢谢!
答案 0 :(得分:2)
当您想要根据CurrentRating进行排名时,您的查询应该是这样的。
<强>查询强>
SELECT
Leaderboard.PlayerName
, Leaderboard.PlayerRating
, (@rank := @rank + 1) AS rank
FROM
Leaderboard
CROSS JOIN(
SELECT
@rank := 0
)
AS
init_user_variable
ORDER BY
Leaderboard.CurrentRating DESC
当你想要在哪里使用过滤器排名时,你应该在这样的交付表中使用这个查询。
<强>查询强>
SELECT
Leaderboard_ranked.PlayerName
, Leaderboard_ranked.PlayerRating
, Leaderboard_ranked.rank
FROM (
SELECT
Leaderboard.PlayerName
, Leaderboard.PlayerRating
, (@rank := @rank + 1) AS rank
FROM
Leaderboard
CROSS JOIN(
SELECT
@rank := 0
)
AS
init_user_variable
ORDER BY
Leaderboard.CurrentRating DESC
)
AS
Leaderboard_ranked
WHERE
Leaderboard_ranked.PlayerName = 'playername'
PHP MySQLi语法
$connection = mysqli_connect("host/ip", "user", "password", "database");
$result = mysqli_query($connection, [query]);
while($row = mysqli_fetch_array($result)) {
echo $row['PlayerName'] . " " . $row['PlayerRating'] . " " . $row['rank'] "<br />"
}
答案 1 :(得分:0)
SELECT COUNT(*) FROM Leaderboard WHERE CurrentRating > ?
用户当前评级作为参数应该或多或少