条目排名和分组依据
我有一个网站,人们可以在其中保存游戏中的高分。我一直在尝试通过查找更高的其他高分数量来为玩家的高分分配排名。因此,如果查询找到 5 个人的高分较高,则该玩家的高分排名将为 6。
事实是,数据库中可以为每个用户记录多个分数(针对同一游戏)。这就是为什么当我只想显示玩家在游戏中的最佳得分(而不是他在该游戏中的所有得分)时使用GROUP BY user。
这是我现在使用的代码。它不起作用,因为查询似乎总是返回 2(就像它总是返回只有一个分数比玩家的最高分高一样)。如果我删除temp GROUP BY user,它会返回一个半正确的值,因为计算给定游戏中每个玩家的所有分数(如果一个玩家在游戏中作为多个分数)。
$count3 = mysql_result(mysql_query("SELECT COUNT(*) + 1 as Num FROM (SELECT * FROM ava_highscores WHERE game = $id AND leaderboard = $get_leaderboard[leaderboard_id] AND score > '$highscore2[score]') temp GROUP BY user");
I have a website where people are saving highscores in games. I've been trying to assign a rank to a player's highscore by finding the number of other highscores that are higher. So if the query finds 5 people with higher highscores, the player's highscore rank will be 6.
The thing is that more than one score (for the same game) can be recorded in the database for every user. This is why I'm using GROUP BY user when I want to display only a player's best score in a game (not all of his scores in that game).
Here's the code I am using now. It doesn't work, since the query seems to always return 2 (like if it was always returning that there was only one score higher than the player's highscore). If I remove temp GROUP BY user, it returns an half-correct value, since counting all the scores (if a player as multiple scores in a game) from every player in a given game.
$count3 = mysql_result(mysql_query("SELECT COUNT(*) + 1 as Num FROM (SELECT * FROM ava_highscores WHERE game = $id AND leaderboard = $get_leaderboard[leaderboard_id] AND score > '$highscore2[score]') temp GROUP BY user");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用
GROUP BY
时,COUNT
返回每个组的行数,而不是结果集中所有行的单个计数。请改用COUNT(DISTINCT ...)
。而且你实际上并不需要内部选择。您可以将其全部编写为单个查询:注释
score
列是数字类型(而不是 varchar 类型),以便比较正确进行。(game,leaderboard,score)
上添加索引将使查询更加高效。索引中列的顺序也很重要。When you use
GROUP BY
thenCOUNT
returns a count of rows per group rather than a single count of all rows in the result set. UseCOUNT(DISTINCT ...)
instead. Also you don't actually need the inner select. You can write it all as a single query:Notes
score
column is a numeric type (not a varchar type) so that the comparison works correctly.(game, leaderboard, score)
will make the query more efficient. The order of the columns in the index is also important.