M
M
Max Payne2017-09-13 15:01:29
MySQL
Max Payne, 2017-09-13 15:01:29

How to get MySql user position?

I use the following code to generate a list of the most active users:

SELECT user_id, COUNT(*) as user_commands FROM `log` GROUP BY user_id ORDER BY user_commands DESC

For example, I know a specific user_id - how can I find out its position in this list?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-09-14
@YardalGedal

In general, you can do this:

SET @number := 0;
SELECT
  rating.*
FROM
  (
    SELECT
      (@number := @number + 1) AS number,
      user_id,
      COUNT(*) AS user_commands
    FROM
      `log`
    GROUP BY
      user_id
    ORDER BY
      user_commands DESC
  ) AS rating
WHERE
  rating.user_id = 2

But you should understand that such queries are not rational, and they are not suitable for large loads / data, so I would recommend making a separate table that aggregates user ratings

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question