我的代码显示错误的排名值

时间:2014-01-19 00:42:32

标签: mysql sql

我的排名错误但正确的值按降序排列:

create table uservotes(id int, name varchar(50), vote int,state int);

INSERT INTO uservotes VALUES
(1, 'A', 34,1),
(2, 'B', 80,1),
(3, 'bA', 30,1),
(4, 'C', 8,1),
(5, 'D', 4,1),
(6, 'E', 14,2),
(7, 'F', 304,2),
(8, 'AA', 42,3),
(9, 'Ab', 6,3),
(10, 'Aa', 10,3);

create table states(state_id int, name_state varchar(50));

INSERT INTO states VALUES
(1, 'CA'),
(2, 'AL'),
(3, 'AZ');

使用下面的代码,我的等级为6,2,1,3,5而不是1,2,3,4,5为什么?价值也是正确的而不是等级。请让我知道我的错误在哪里。 我非常感谢任何帮助。谢谢你。

select uv.*,
      @curRank := @curRank + 1 AS rank
from  uservotes uv cross join 
     states s 
     on uv.state = s.state_id, (select @curRank := 0) const
where name_state = 'CA'
order by vote desc limit 5;

1 个答案:

答案 0 :(得分:3)

试试这个。它的工作原理如此SQLFiddle:http://sqlfiddle.com/#!2/35c6c/33

select agg.*, @curRank := @curRank + 1 AS rank from
(
select uv.*
from uservotes uv cross join 
 states s 
 on uv.state = s.state_id
where name_state = 'CA'
order by vote desc limit 5) as agg, (select @curRank := 0) const;

<强>结果:

ID  NAME    VOTE    STATE   RANK
2   B   80  1   1
1   A   34  1   2
3   bA  30  1   3
4   C   8   1   4
5   D   4   1   5