We have a game where players run through a map, and are scored for it. We need to find out which attempts had the high score on each map, and set their isHighScore
flag to true. Only one attempt can have the high score for each map - if two attempts have the same score, only the attempt which came first chronologically should have its isHighScore
flag set.
The SQL we currently have looks like this:
UPDATE attempts AS A1
SET isHighScore = 1
WHERE A1.ID =
(
SELECT A2.ID
FROM (SELECT ID, score, mapID, `date` FROM attempts) AS A2
WHERE A2.mapID = A1.mapID
ORDER BY A2.score DESC, A2.date ASC
LIMIT 1
)
(The (SELECT ... FROM attempts)
subquery is due to this issue)
The above takes longer than the timeout to run on a table with around 75k entries (and yes, there is an index on mapID, score, date
). I assumed it was because the innermost query copies the entire attempts
table to a temp-table, but moving the WHERE mapID = A1.mapID
conditional into that query gives a syntax error, so I'm not sure what to do about that. Also, the inner-query runs once for every row - maybe there's a way to fix that?
Does anyone know of a better way to write this query in MySQL?