查询以获取分组项目排名?

时间:2013-02-27 08:48:31

标签: mysql sql

我有各种用户的点击表:

HITS:
id | userid
1  | 1     
2  | 1     
3  | 2     
4  | 1     
5  | 2     
6  | 2     

我希望以最快的方式获取按ID排名的这些项目的列表。所以这个:

HITS RANKED:
id | userid | ranks
1  | 1      | 1
2  | 1      | 2
3  | 2      | 1
4  | 1      | 3
5  | 2      | 2
6  | 2      | 3

我想避免将两个表相互连接,因为当表变大时这将永远存在。还有其他建议吗?

1 个答案:

答案 0 :(得分:1)

SELECT  ID, 
        UserID, 
        Ranks
FROM
    (
        SELECT  id,
                userid,
                @group:=CASE WHEN @temp <> userid THEN 1 ELSE @group+1 END AS ranks,
                @temp:=userid AS clset
        FROM    (SELECT @group:= 0) s,
                (SELECT @temp:= 0) c,
                (SELECT * FROM hits ORDER BY userid, id) t
    ) x
ORDER   BY ID