简体   繁体   中英

Query to get grouped items ranked?

I have a table of hits for various users:

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

I want the fastest possible way to get a list of these items ranked by ID. So this:

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

I want to avoid joining two tables to each other, as this takes forever when the tables get big. Any other suggestions?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM