如何从mysql表中计算Rank

时间:2012-09-22 05:36:25

标签: mysql sql

  

可能重复:
  Mysql rank function

我在MySQL中有以下表格:

===================================================================
id  | member|  total_correct_question | time_taken_in_seconds |

===================================================================
1   |  abc  |     2                    |       4              |
2   |  def  |     3                    |       6              |
3   |  ghi  |     3                    |       4              |
4   |  jkl  |     3                    |       5              |
====================================================================

我想从mysql查询中显示每个用户的排名。任何人都可以建议我对此进行查询吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

  SELECT @i:=@i+1 AS rank,a.*
  FROM
      (SELECT * 
       FROM   Your_table  
       ORDER BY total_correct_question DESC,
                time_taken_in_seconds)a,(SELECT @i:=0) r  


SQL Fiddle demo

答案 1 :(得分:1)

您可以创建一个从原始查询中生成笛卡尔积的子查询,最有趣的是您可以将其递增一个(然后生成RANK数)。

SELECT    @rankNo:=@rankNo+1 RankNo,
          a.*
FROM      Table1 a, (SELECT @rankNo:=0) r 
ORDER BY `total_correct_question` DESC,
         `time_taken_in_seconds` ASC

SQLFiddle Demo