How best to get someone's 'rank' from a scores table with php and mysql without looping

前端 未结 3 877
深忆病人
深忆病人 2020-11-29 10:38

My table will hold scores and initials.

But the table wont be ordered.

I can get the total row count easy enough and I know I can get all of them and Order B

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 11:22

    See this answer: https://stackoverflow.com/a/8684441/125816

    In short, you can do something like this:

    SELECT id, (@next_rank := IF(@score <> score, 1, 0)) nr, 
               (@score := score) score, (@r := IF(@next_rank = 1, @r + 1, @r)) rank 
    FROM rank, (SELECT @r := 0) dummy1
    ORDER BY score DESC;
    

    And it will produce a result like this:

    +------+----+-------+------+
    | id   | nr | score | rank |
    +------+----+-------+------+
    |    2 |  1 |    23 |    1 |
    |    4 |  1 |    17 |    2 |
    |    1 |  0 |    17 |    2 |
    |    5 |  1 |    10 |    3 |
    |    3 |  1 |     2 |    4 |
    +------+----+-------+------+
    

    Note that users with equal scores have equal ranks. :-)

提交回复
热议问题