简体   繁体   中英

MySQL how to get user rank by votes amount

I have two tables. One "user" and one "votes", each user can have n votes. Now I select a list of users and output it. It works well with votes as COUNT in a LEFT JOIN, but now I want to calculate the RANK (1st, 2nd, 3rth, ...) of the user.

Theoretically very easy with ORDER BY Votes, but I also allow my users to SORT BY user date (when they joined). And I also have a pagination with a LIMIT in my query. So how do I solve this as best?

$user_sql   = $db->query("SELECT u.*, COUNT(v.voteId) AS user_votes 
                          FROM cs_users AS u
                          LEFT JOIN cs_users_votes AS v 
                          ON u.userId = v.voteUserId");

(Basic query, but with pagination and sorter ORDER BY / LIMIT etc. will be added)

Hope you can help!

Well, to count rank you can use the ranking function found here It will rank every user, taking in consideration result ties. If you add pagination you might try to pass the result from the previous page recursively.

As for the function itself

SET @curRank :=0, @prevRank := NULL;
SELECT u.*, COUNT(v.voteId) AS user_votes,
CASE 
WHEN @prevRank = id THEN @curRank 
WHEN @prevRank := id THEN @curRank := @curRank + 1
END AS rank
FROM cs_users AS u
LEFT JOIN cs_users_votes AS v 
ON u.userId = v.voteUserId

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