I’ve got reporting of a user’s score every time it happens. Now I want to show the best score a user has had. The table set up is like this:
Player(id, name)
PlayerHasAchievement(id, playerId,
achievementId)Achievement(id, type, amount, time)
This is what I have right now:
SELECT MAX(ach.amount) as amount, p.username, ach.time
FROM achievement as ach
INNER JOIN playerHasAchievement as playAch ON ach.id = playAch.id
INNER JOIN player as p ON p.userId = playAch.userid
WHERE ach.type = 2
GROUP BY amount
ORDER by `amount` DESC
LIMIT $amount
I tried to select it distinctly but it didn’t work.
The problem is the the
ach.timeyou are getting is not the same row as theMAX(amount). Join another subquery to get theMAX(amount)first.Note: In the table definitions you posted,
playerHasAchievementhas a fieldplayerIdnotuserIdThe reason why we group the outer query, is to avoid ties – say a player had the same score twice.