Mysql RANK没有为每个类别提供RANK

时间:2014-10-23 12:16:12

标签: mysql sql

我尝试了以下内容,但并没有对每个类别进行排名。而是在不考虑类别的情况下为所有记录排名。我希望每个类别重新出现RANK

select  rs.Section,rs.Field1,rs.Field2 , 
@curRank := @curRank + 1 AS rank 
from (
select rs.Field1,rs2.Field2 
from table rs
inner join table2 rs2 on rs.Field1=rs2.Field1
group by rs.Section,rs.Field1 
)rs,  (SELECT @curRank := 0) r

实际输出:(来自Mysql输出)

Category Field1 Field2 Rank
Male     10     10     1
Male     11     10     2
Male     12     10     3
....
FeMale   10     10     11
FeMale   11     10     12
FeMale   12     10     13
....

预期输出

Category Field1 Field2 Rank
Male     10     10     1
Male     11     10     2
Male     12     10     3
....
FeMale   10     10     1
FeMale   11     10     2
FeMale   12     10     3
....

1 个答案:

答案 0 :(得分:2)

我假设您正在使用的查询是:

select  rs.Category, rs.Field1, rs.Field2, @curRank := @curRank + 1 AS rank 
from (select rs.Cateogry, rs.Field1, rs2.Field2 
      from table rs inner join
           table2
           rs2 on rs.Field1 = rs2.Field1
      group by rs.Category, rs.Field1, rs.Field2
     ) rs cross join
     (SELECT @curRank := 0) vars
order by cateogry, field1;

或类似的东西,字段名称是一致的。您需要一个变量来指定分组。以下内容将起作用:

select  rs.Category, rs.Field1, rs.Field2,
        (@curRank := if(@c = Category, @curRank + 1,
                        if(@c := Category, 1, 1)
                       )
        ) AS rank 
from (select rs.Cateogry, rs.Field1, rs2.Field2 
      from table rs inner join
           table2
           rs2 on rs.Field1 = rs2.Field1
      group by rs.Category, rs.Field1, rs.Field2
     ) rs cross join
     (SELECT @curRank := 0, @c := NULL) vars
order by cateogry, field1;

请注意,两个变量的赋值都出现在一个语句中。这很重要,因为MySQL不保证select子句中表达式的评估顺序。另请注意group by的明确使用。我建议你使用它,而不是依赖group by按特定顺序产生结果(在最新版本的MySQL中不推荐使用该功能)。