Question

I need a list of the top ranked players in a game. The rank is calculated on the fly and the data is taken from two tables. I managed to order them in the correct way but the @rank:=0 -> @rank:=@rank+1 trick, where an additional field,named rank, is calculating the position of the player that corresponds to a specific ordering parameter, doesn't return the right rank order. This is what I have:

SET @rank := 0;
SELECT 
@overall := u_p_s.exploration + u_p_s.story + u_p_s.collection + u_p.experience AS overall,
@rank := @rank + 1 AS rank,
u.nick, u.user_id, u_p_s.exploration, u_p_s.story, u_p_s.collection, u_p.experience
FROM user AS u
INNER JOIN user_profile_stats AS u_p_s ON u_p_s.user_id = u.user_id
INNER JOIN user_profile AS u_p ON u_p.user_id = u.user_id
ORDER BY overall DESC
LIMIT 0 ,20;

The result is correct overall order but incorrect rank order. I can always count the rows and get the rank in the application layer but I still need to know what is wrong with my query here. If you have any propositions of how to calculate a specific user's rank I am open to suggestions. I have seen a lot of similar questions but none of them calculates the ranking parameter on the fly (overall) and since I am not the best at MySql, I kindly ask for your help. Thank you.

Solution:

SET @rank:=0;
SELECT 
@rank := @rank +1 AS rank,
nick, user_id, story, overall, collection, experience, exploration
FROM (
SELECT @overall := u_p_s.exploration + u_p_s.story + u_p_s.collection + u_p.experience AS overall, 
u.nick, u.user_id, u_p_s.story, u_p.experience, u_p_s.collection, u_p_s.exploration
FROM user AS u
INNER JOIN user_profile_stats AS u_p_s ON u_p_s.user_id = u.user_id
INNER JOIN user_profile AS u_p ON u_p.user_id = u.user_id
ORDER BY overall DESC
LIMIT 0 , 20
) AS result
Was it helpful?

Solution

I think the problem is that you calculate the rank first before the ordering takes place.

What if you try smth like this:

SELECT
@rank := @rank + 1 AS rank,
overall, u.nick, u.user_id, ...
FROM (SELECT ... <your query including ORDER BY>)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top