MySQL "Rank in Record" -Query

Hi, encoders around the world,

I am working on a project in which users can do certain things and get points for it. To simplify this question, let's say we got 2 user tables and points .

-- table user       -- table points
+---------------+    +-----------------------------+
|  id  |  name  |    |  id  |  points  |  user_id  |
+---------------+    +-----------------------------+
|  1     Tim    |    |  1      5          1        |
|  2     Tom    |    |  2      10         1        |
|  3     Marc   |    |  3      5          1        |
|  4     Tina   |    |  4      12         2        |
|  5     Lutz   |    |  5      2          2        |
+---------------+    |  6      7          1        |
                     |  7      40         3        |
                     |  8      100        1        |
                     +-----------------------------+

Now, to get the full list of records, I use the following query

SELECT u.*, SUM( p.points ) AS sum_points
FROM user u
LEFT JOIN points p ON p.user_id = u.id
GROUP BY u.id
ORDER BY sum_points DESC

the result is a great list of records with all users from the first to the last

+------------------------------+
|  id  |  name  |  sum_points  |
+------------------------------+
|  1     Tim       127         |
|  3     Marc      40          |
|  2     Tom       14          |
|  4     Tina      0           |
|  5     Lutz      0           |
+------------------------------+

Let's get back to the question itself. In the profile of one user, I would like to show his rating in the list of records.

Is it possible to do this using one query, which simply shows that, for example, Tom (id = 2) takes place 3?

Thank you so much: -)

+3
2

, : " @this_user":

select count(*) + 1 from 
(
    /* list of all users */
    SELECT SUM( p.points ) AS sum_points
    FROM user u
    LEFT JOIN points p ON p.user_id = u.id
    GROUP BY u.id        
) x
/* just count the ones with higher sum_points */
where sum_points > (select sum(points) from points where user_id = @this_user)

, 1 0-based

+4
SELECT  q.*,
        @r := @r + 1 AS rank
FROM    (
        SELECT  @r := 0
        ) vars,
        (
        SELECT  u.*,
                SUM(p.points) AS sum_points
        FROM
                user u
        LEFT JOIN
                points p
        ON      p.user_id = u.id
        GROUP BY
                u.id
        ORDER BY
                sum_points DESC
        ) q
+1

Source: https://habr.com/ru/post/1729585/


All Articles