2016-10-10 75 views
2

我想了解在MySQL中使用變量的密集等級。瞭解MySQL中的等級功能

我創建了一個表,如:

create table scores (id int,score float); 

這樣插入的值:

insert into scores values(1,3.50); 
insert into scores values(2,3.65); 
insert into scores values(3,4.00); 
insert into scores values(4,3.85); 
insert into scores values(5,4.00); 
insert into scores values(6,3.65); 

我寫了使用分數這樣的排名表中查詢:

set @rank=0; 
[email protected]=''; 
select score, 
    (@rank := if(@score = score, 
       @rank, 
       if(@score := score,  
        @rank+1, 
        @rank      
       ) 
       )     
    ) as rank 
from scores 
order by score desc; 

當我運行查詢「沒有」按分數desc 輸出是這樣的:

score rank 
3.5  1 
3.65 2 
4  3 
3.85 4 
4  5 
3.65 6 

當我跑了按分數降序查詢「與」命令,我得到的輸出,它是這樣的:

score rank 
4  1 
4  1 
3.85 2 
3.65 3 
3.65 3 
3.5  4 

使用下面的代碼片段時有什麼內部發生?

select score, 
    (@rank := if(@score = score, 
       @rank, 
       if(@score := score,  
        @rank+1, 
        @rank      
       ) 
       )     
    ) as rank 
from scores 
+0

哪部分你不完全明白嗎?有什麼是你想不到的嗎? –

+0

@JanZeiseweis如何內部比較正在發生和跑步更新?這是我不清楚的地方。感謝您的輸入 – sritharan

回答

0

您的排名算法基本上只是比較每一行的分數與前一行或''(第一行)的分數。 如果得分相同,則返回相同的等級,如果得分改變,則等級增加1。

編輯

順便說一句,它的排序結果集後執行此操作。

+0

比較正在發生的內部和排名更新?這是我不清楚的地方。感謝您的輸入 – sritharan

+0

答案不清楚嗎?這裏最重要的是,每行的分數與之前(上面)的行進行比較。 'if(@score = score,' @score是前一行的得分值,而 '得分'是當前行的得分值 如果它們不同,'@ score'值是被'score'和'@ rank'覆蓋的值增加1('@ rank + 1')。 –