[英]Order by descending and returning the record number to use for ranking
I'm trying to rank users very simply by their reputation, which is stored as an int
column in a MySQL table of users. 我试图非常简单地根据用户的信誉对用户进行排名,信誉以
int
列的形式存储在用户的MySQL表中。 In order to find out which users have the highest reputation from highest to lowest, I would do something like: 为了找出从最高到最低的信誉最高的用户,我将执行以下操作:
SELECT * FROM users ORDER BY reputation DESC
Which would give me users ordered by highest reputation to lowest. 这将使我按信誉排名从高到低排序。 Say user
Tim
shows up as the 3rd record. 假设用户
Tim
显示为第三条记录。 How do I return which # record he is in that order, ie his rank? 如何返回他按该顺序排列的#条记录,即他的等级? This seems really simple but I'm drawing a blank on how to do it.
这看起来真的很简单,但是我在如何做上空白。 Essentially I want the record # after ordering to say "he is the user with the third highest reputation".
从本质上讲,我要在命令说“他是信誉第三高的用户”之后记录#。 Alternatively, is this the wrong way to go about ranking?
另外,这是进行排名的错误方法吗?
I can specify a user in users
by the column user_id
and just mainly want to return the user's rank in one query, if possible. 我可以通过
user_id
列在users
指定一个用户,如果可能的话,我主要只是想在一次查询中返回该用户的排名。
I'm using Laravel as a framework if anyone knows a shortcut using that, but just generally with SQL would be fine too. 如果有人知道使用Laravel的快捷方式,我将使用Laravel作为框架,但是通常使用SQL也可以。
Are you looking for something like this? 您是否正在寻找这样的东西?
set @rank:= 0;
SELECT (@rank:= @rank+ 1) AS Rank , users.* FROM users ORDER BY reputation DESC;
This will increment @rank for each resulting record. 这将为每个结果记录增加@rank。 For a specific user use:
供特定用户使用:
SELECT T.reprank
FROM (SELECT @rank := @rank + 1 AS reprank,
users.*
FROM users,
(SELECT @rank := 0) rnk
ORDER BY reputation DESC) AS T
WHERE id = 23
This is similar to the Sam D answer, but it puts everything into a single query: 这类似于Sam D的答案,但是将所有内容放入一个查询中:
SELECT
@rank := @rank + 1 AS RepRank,
users.*
FROM users, (SELECT @rank := 0) rnk
ORDER BY reputation DESC;
To limit results to a specific user you'll need to do an outer query - there's really no way around it. 要将结果限制为特定用户,您需要执行外部查询-确实没有解决方法。 Here's how (note that the inner query is the same as the query shown above):
方法如下(请注意,内部查询与上面显示的查询相同):
SELECT * FROM (
SELECT
@rank := @rank + 1 AS RepRank,
users.*
FROM users, (SELECT @rank := 0) rnk
ORDER BY reputation DESC
) RankedUsers
WHERE User_ID = 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.