I have a table consisting of records of every match that every player has played. I've gotten a pretty good head start from the top answer of this question: Ranking with millions of entries, and am currently using this query to retrieve each player's highest score and their rank:
SET @rank=0;
SELECT user_id, score, rank FROM (
SELECT *, @rank := @rank + 1 as rank
FROM high_scores
JOIN (
SELECT user_id as user_id2, MAX(score) AS max_score
FROM high_scores
GROUP BY user_id2
ORDER BY max_score DESC) AS max_score_table
ON max_score = high_scores.score AND high_scores.user_id = user_id2) derived_table
ORDER BY rank;
Again, this gives me a nice ordered list of each player's top score and its rank; However, I'd also like to be able to supply a specific user_id
and filter the results down to this user's score as well as X amount of surrounding higher and lower scores.
I would think I'd need to perform a SELECT ... WHERE
on "derived_table" for the user id
and use the returned row's 'rank'
to filter the top-level SELECT
statement, but in addition to the query not even being accepted ('derived_table doesn't exist'), the way I was doing it would have required me to re-query derived_table twice (for a greater-than and less-than test), making the query even less efficient than it probably should be.
How can I filter the full list of high scores and ranks down to a single user_id
's entry and X amount of surrounding entries? Any insight on the code I'm trying to come up with (or the code I currently have) would be greatly appreciated.