如果我们有表格,那么排行榜最有效的SQL查询是什么:
[UserID], [Points]
我希望结果按点和Rank列排序。
答案 0 :(得分:2)
在SQL Server 2008中,您可以使用Ranking functions:
SELECT UserId,
Points,
RANK() OVER(ORDER BY Points DESC) AS Rank
FROM LeaderBoards
ORDER BY Points DESC
A MySql rank could be something like this:
SELECT UserId,
Points,
@curRank := @curRank + 1 AS Rank
FROM LeaderBoards l, (SELECT @curRank := 0) r
ORDER BY Points DESC
答案 1 :(得分:1)
查询应为:
SELECT UserID,Points FROM table ORDER BY Points
在您使用的任何显示技术(即php等)中生成排名列可能更容易。它可以在大多数SQL中完成,但语法会有所不同。
答案 2 :(得分:0)
这是一个利用join的解决方案:
SELECT t1.UserID, t1.Points, COUNT(t2.Points) AS Rank
FROM LeaderBoards t1
JOIN LeaderBoards t2 ON t1.Points < t2.Points OR (t1.Points=t2.Points and t1.UserID = t2.UserID)
GROUP BY t1.UserID, t1.Points
ORDER BY t1.Points DESC, t1.UserID DESC;
我在MySQL上测试了这个。有关此更详细的文章,请参阅: http://www.artfulsoftware.com/infotree/qrytip.php?id=460