Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL update statement to store ranking positions

I'm trying to get my head around a query and I just can't figure it out. I would appreciate if someone give me a pointer. As a simple example of what I'm trying to achieve, I have these records in the database

Score|Ranking
-------------
100  |0
200  |0
300  |0

And I would like the Ranking field to contain 1,2,3 based on who's got the highest score so the result should be:

Score|Ranking
-------------
100  |3
200  |2
300  |1

At the moment, I'm doing a for next loop for all these records but given that in reality that could be a few thousand - that could take forever! Does anyone have an idea on a magic query which would do this in one go?

like image 214
user385762 Avatar asked Jul 07 '10 16:07

user385762


People also ask

Does MySQL support rank function?

MySQL uses a ranking function that allows us to rank each row of a partition in the databases. The ranking functions are also a sub-part of a window function in MySQL. The ranking functions in MySQL can be used with the following clauses: They always work with the OVER()

Can we use order by in update query in MySQL?

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used.


2 Answers

Here's a way to do it:

SET @r=0;
UPDATE table SET Ranking= @r:= (@r+1) ORDER BY Score DESC;

/* use this if you just want to pull it from the db, but don't update anything */
SET @r=0;
SELECT *, @r:= (@r+1) as Ranking FROM table ORDER BY Score DESC;
like image 127
quantumSoup Avatar answered Sep 23 '22 01:09

quantumSoup


In MySQL, you can use row_number.

Here's an example of using it in a SELECT:

select @rownum:=@rownum+1 ‘rank’, p.* 
from player p, (SELECT @rownum:=0) r 
order by score desc;

If you INSERT INTO using a SELECT like this, you will get your rankings.

like image 34
DOK Avatar answered Sep 25 '22 01:09

DOK