Search code examples
mysqlrating

MySQL select user's place


I have a table users:

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

How I can select user's place ordering by rating where id = N and that users with similar rating have the same place in the top?

UPD: I want to output:

If userid = 1, his rank is 2, if userid = 2, his rank is 5, if userid = 3, rank is 1, ... But if userid = 4 or 6 their rank are 4 because rates are similar.


Solution

  • I think you want to find the rating for 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;
    

    Example @ sqlfiddle

    If you don't want to change the order of records in output then try this:

    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;