复杂的MySQL排名查询与关系

时间:2011-01-31 07:02:13

标签: sql mysql ranking

假设我有下表:

id | name | points  
-------------------
1  | joe  | 100  
2  | bob  | 95  
3  | max  | 95  
4  | leo  | 90

我可以像这样生成反向排名记录集:

id | name | points | rank  
--------------------------
4  | leo  | 90     | 1  
3  | max  | 95     | 2.5  
2  | bob  | 95     | 2.5   
1  | joe  | 100    | 4  

2 个答案:

答案 0 :(得分:1)

这是一个完整的示例,包含此示例表

create table tpoints (id int, name varchar(10), points int);
insert tpoints values
(1  ,'joe', 100 ),
(2  ,'bob', 95  ),
(3  ,'max', 95  ),
(4  ,'leo', 90  );

MySQL查询

select t.*, sq.`rank`
from
(
    select
       points,
        @rank := case when @g = points then @rank else @rn + (c-1)/2.0 end `rank`,
       @g := points,
       @rn := @rn + c
    from 
       (select @g:=null, @rn:=1) g,
        (select points, count(*) c
        from tpoints
        group by points
        order by points asc) p
) sq inner join tpoints t on t.points = sq.points
order by t.points asc;

与执行相关的交叉(自我)联接相比,它还具有表现良好的优势。

  • 1x通过tpoints汇总成组
  • 有关系的等级计算
  • 1x加入表格,将排名与记录对比。

答案 1 :(得分:0)

不会将“2.5”作为排名值,但如果使用,重复项将具有相同的数字:

  SELECT x.id, 
         x.name,
         x.points,
         (SELECT COUNT(*)
            FROM YOUR_TABLE y
           WHERE y.points <= x.points) AS rank
    FROM YOUR_TABLE x
ORDER BY x.points