MySQL查询获得特定排名

时间:2016-08-04 04:54:48

标签: mysql sql performance mysql-variables

我对MySQL数据库的查询工作方式是这样得到的结果:

rake db:migrate VERSION=0

我从中获得此结果的查询如下(我隐藏主查询而不是怀疑太多代码):

> Rank  Gold    Silver  Bronze  Total 
> 1     76      78      77      231 
> 2     4       5       6       15 
> 3     4       1       1       6
> 4     3       0       0       3 
> 5     2       1       1       4 
> 5     2       1       1       4
> 6     2       0       0       2
> 7     1       1       1       3
> 8     1       1       0       2
> 9     1       0       2       3
> 9     1       0       2       3
> 9     1       0       2       3
> 10    0       1       0       1

但是上面的重复,我想调整Rank coloumn(和我的查询),根据重复的前一行增加它,即:

select
    CASE
        WHEN (@Gold=T.Gold and @Silver=T.Silver and @Bronze=T.Bronze) THEN @rownum ELSE @rownum:=@rownum+1 end as Rank,        

        (@Gold:=T.Gold) Gold,
        (@Silver:=T.Silver) Silver,
        (@Bronze:=T.Bronze) Bronze,
        T.Total

from

(MAIN_QUERY) T,

(SELECT @rownum:=0) r, 
    (SELECT @Gold:=0) g,
    (SELECT @Silver:=0) s,
    (SELECT @Bronze:=0) b

   order by Gold desc, Silver DESC, Bronze DESC

等等。 你能帮助我得到这个结果吗?

1 个答案:

答案 0 :(得分:2)

也许另一个变量可以做到这一点:

SELECT @rownum := @rownum + 1, 
       CASE 
         WHEN ( @gold = T.gold 
                AND @silver = T.silver 
                AND @bronze = T.bronze ) THEN @rank := @rank 
         ELSE @rank := @rownum 
       END                     AS Rank, 
       ( @gold := T.gold )     Gold, 
       ( @silver := T.silver ) Silver, 
       ( @bronze := T.bronze ) Bronze, 
       T.total 
FROM   (MAIN_QUERY) T 
       CROSS JOIN (SELECT @rownum := 0, 
                          @gold := 0, 
                          @silver := 0, 
                          @bronze := 0, 
                          @rank := 0) v 
ORDER  BY gold DESC, 
          silver DESC, 
          bronze DESC 

Here is a demo

注意: 如果您的数据的所有列都为0,则无效。