如何根据点数在查询中给出排名

时间:2012-01-10 13:57:04

标签: mysql

根据我的需要,以下查询工作正常。所有用户都获得独特的 RANKS (相同点的用户不应该获得相同的排名)

SELECT  
    id, 
    first_name, 
    email, 
    (SELECT 
        rank 
    FROM (  SELECT 
            @rownum:=@rownum+1 rank, 
            u.id AS user_id, 
            points 
        FROM 
            user_master u, (SELECT @rownum:=0) r
        ORDER BY 
            points 
        DESC) AS tmp 
    WHERE 
        user_id = um.id) AS Rank,
    registered_date AS registered,
    um.points as Points
FROM 
    user_master um
ORDER BY 
    um.id ASC 

现在我想查看此查询,它给出了错误消息

  

View的SELECT包含FROM子句中的子查询

我还尝试首先查看用户排名以合并2个不同的视图。以下查询提供了完美的用户排名,但是当我尝试查看此内容时:

SELECT 
    @rownum:=@rownum+1 rank, 
    id AS user_id, 
    points 
FROM 
    user_master u, (SELECT @rownum:=0) r
ORDER BY 
    points 
DESC 

..它给了我错误信息:

  

View的SELECT包含一个变量或参数

在此查询中是否还有其他方法可以应用排名(即使点数相同,Rank也必须是唯一的)。

1 个答案:

答案 0 :(得分:2)

放手一搏:

create view test_view as SELECT t.id,t.first_name,t.email,
    (select sum(case when t1.points > t.points then 1
                     when t1.points = t.points and t1.id < t.id then 1
                else 0 end) from user_master t1)+1 as rank, t.registered_date AS registered,
t.points as Points 
from user_master t
order by points desc;