7

我有一个表用户:

id  |   rating
1       4
2       -1
3       12
4       0
5       2
6       0

如何通过评分来选择用户的位置排序,id = N并且具有相似评分的用户在顶部具有相同的位置?

UPD:我想输出:

如果userid = 1, 他的rank is 2, 如果userid = 2, 他的rank is 5, 如果userid = 3, rank is 1, ... 但是如果userid = 4或者6他们的rank are 4因为利率是相似的。

4

2 回答 2

5

我想你想找到 asll user_id's` 的评分:

SELECT id,
       IF(rating <> @var_rating_prev, (@var_rank:= @var_rank + 1), @var_rank) AS rank,
       (@var_rating_prev := rating) AS rating
FROM table_name a,(SELECT @var_rank := 0, @var_rating_prev := 0) r
ORDER BY rating DESC;

例子@sqlfiddle

如果您不想更改输出中记录的顺序,请尝试以下操作:

SELECT a.*, b.rank
FROM test_table a
     INNER JOIN (
            SELECT id,
                   IF(rating <> @var_rating_prev, (@var_rank:= @var_rank + 1), @var_rank) AS rank,
                   (@var_rating_prev := rating) AS rating
            FROM test_table a,(SELECT @var_rank := 0, @var_rating_prev := 0) r
            ORDER BY rating DESC
        ) b
         ON a.id = b.id
ORDER BY a.id;
于 2012-08-31T11:30:58.963 回答
2
SELECT COUNT(*)+1 `rank`
FROM table_name
WHERE rating > (SELECT rating
                FROM table_name
                WHERE id = N)
于 2012-08-31T11:46:47.920 回答