使用where子句在mysql中按降序获取人员的等级

时间:2014-01-01 21:41:59

标签: php mysql sql

我已经尝试了http://sqlfiddle.com/#!2/df2ec/1来获取数据:我正在尝试获得名称A的等级4,但我无法做到。

SELECT @rownum := @rownum + 1 AS rank, name, vote 
FROM uservotes, (SELECT @rownum := 0) t ORDER BY vote DESC

在数据表中:

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

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

我无法获得where子句。基本上我想知道哪个等级是基于投票的名称。我试过:

SELECT @rownum := @rownum + 1 AS rank, name, vote 
FROM uservotes WHERE name= A , (SELECT @rownum := 0) t ORDER BY vote DESC

但是我收到了一个错误。我真的很感激任何帮助。谢谢你。

错误:

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第2行使用“(SELECT @rownum:= 0)t ORDER BY vote DESC”附近使用正确的语法:SELECT @rownum:= @rownum + 1 AS等级,名称, vote FROM uservotes WHERE name = A,(SELECT @rownum:= 0)t ORDER BY vote DESC

3 个答案:

答案 0 :(得分:1)

1)试试这个:

SELECT 
    @i:=@i+1 AS rn, 
    t.*
FROM 
    uservotes AS t,
    (SELECT @i:=0) AS tbl
    ORDER BY vote desc

2)然后获取A的特定行很容易:

select * From
(
SELECT 
    @i:=@i+1 AS rn, 
    t.*
FROM 
    uservotes AS t,
    (SELECT @i:=0) AS tbl
ORDER BY vote desc

) x where x.name = 'A'

答案 1 :(得分:0)

SELECT @rownum := @rownum + 1 AS rank, name, vote 
FROM uservotes, (SELECT @rownum := 0) t where name='A' ORDER BY vote DESC

获得排名:

select rank, name, vote
from (SELECT @rownum := @rownum + 1 AS rank, name, vote 
FROM uservotes, (SELECT @rownum := 0) t ORDER BY vote DESC) z
where name='A';

答案 2 :(得分:0)

select a.name, (select count(*) + 1 from uservotes b where (a.vote > b.vote)) as rank 
from uservotes a having name="A" order by rank