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?
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()
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With