1

I have the following table on my DataBase: TimeRank(user-id, name, time)

I would like to order the table by time and get the position of an specific ID on the table, for example:

The user nº 68 is on the 3rd position.

I only need to do a query that returns the position of the user.

MySQL don't have the function row_number, so I don't know how to do it.

2 Answers2

1
SELECT x.user-id, 
       x.name,
       x.time,
       x.position
  FROM (SELECT t.user-id,
               t.name,
               t.time,
               @rownum := @rownum + 1 AS position
          FROM TABLE TimeRank t
          JOIN (SELECT @rownum := 0) r
          ORDER BY t.time) x
 WHERE x.user-id = 123

Alternative:

SELECT user-id,
       (SELECT COUNT(*) FROM TimeRank WHERE time <= (SELECT time FROM TimeRank WHERE user-id = 123)) AS position,
       time,
       name
FROM TimeRank
WHERE user-id = 123
Alex
  • 1,857
  • 3
  • 36
  • 51
0

You can generate a position column with a variable

set @pos=0;

select pos,user_id
from (select @pos:=@pos+1 pos,user_id from TimeRank order by time) s
where user_id=68;

If indexing is a concern, you can add a column to your table and update it with

set @pos=0;

update TimeRank set position=(@pos:=@pos+1) order by time;
guigoz
  • 674
  • 4
  • 21