kamikaze_pilot
kamikaze_pilot

Reputation: 14834

getting the ranking of the rows in mysql ORDER BY statements

suppose I have

SELECT * FROM t ORDER BY j

is there a way to specify the query to also return an autoincremented column that go along with the results that specifies the rank of that row in terms of the ordering?

also this column should also work when using ranged LIMITs, eg

SELECT * FROM t ORDER BY j LIMIT 10,20

should have the autoincremented column return 11,12,13,14 etc....

Upvotes: 1

Views: 427

Answers (1)

Code Magician
Code Magician

Reputation: 23972

Oracle, MSSQL etc support ranking functions that do exactly what you want, unfortunately, MySQL has some catching up to do in this regard.

The closest I've ever been able to get to approximating ROW_NUMBER() OVER() in MySQL is like this:

SELECT t.*, 
       @rank = @rank + 1 AS rank
FROM t, (SELECT @rank := 0) r
ORDER BY j

I don't know how that would rank using ranged LIMIT unless you used that in a subquery perhaps (although performance may suffer with large datasets)

SELECT T2.*, rank
FROM (
    SELECT t.*, 
           @rank = @rank + 1 AS rank
    FROM t, (SELECT @rank := 0) r
    ORDER BY j
    ) t2
LIMIT 10,20

The other option would be to create a temporary table,

CREATE TEMPORARY TABLE myRank
(
     `rank` INT(11) NOT NULL AUTO_INCREMENT,
     `id` INT(11) NOT NULL,
     PRIMARY KEY(id, rank)
)

INSERT INTO myRank (id)
SELECT T.id
FROM T 
ORDER BY j

SELECT T.*, R.rank
FROM T
    INNER JOIN myRank R 
        ON T.id = R.id 
LIMIT 10,20

Of course, the temporary table would need to be persisted between calls.

I wish there was a better way, but without ROW_NUMBER() you must resort to some hackery to get the behavior you want.

Upvotes: 1

Related Questions