16

I have a Toplist table and I want to get a user's rank. How can I get the row's index?

Unfortunately, I am getting all rows and checking in a for loop the user's ID, which has a significant impact on the performance of my application.

How could this performance impact be avoided?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tugrul Emre Atalay
  • 918
  • 1
  • 9
  • 28

3 Answers3

27

You can use ROW.NUMBER

This is a example syntax for MySQL

SELECT  t1.toplistId, 
        @RankRow := @RankRow+ 1 AS Rank
FROM    toplist t1
JOIN    (SELECT @RankRow := 0) r;

This is a example syntax for MsSQL

SELECT ROW_NUMBER() OVER(ORDER BY YourColumn) AS Rank,TopListId
FROM TopList
Mad Dog Tannen
  • 7,129
  • 5
  • 31
  • 55
9

You may also do something like this:

SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS MyIndex
FROM TopList
BICube
  • 4,451
  • 1
  • 23
  • 44
5

ROW_NUMBER() MS SQL

Use in your code analytic functions

realnumber3012
  • 1,062
  • 6
  • 10