I have a set of MySQL tables containing information from a football management game.
The tables are:
- Players - playerID (PK), playerName
- Matches - matchID (PK), matchSeason, matchRound, matchType
- PlayersMatch - playerID, matchID (comp PK), matchRating, playerForm, playerAge, position (can be null)
Data stored in these tables are related to the performance of a player. A Player plays in a match and has a rated performance (matchRating). There is a record in PlayersMatch for each match a player participates in, recording the players current form, match performance, their age at the time of the match (for historical purposes) and the position they played in.
Now, currently, I'm using the following query to list the top 10 players from the whole season (best performance in the season overall as opposed to best performance per round):
SELECT playerID, matchID, playerForm, playerAge, MAX(matchRating)
FROM PlayersMatch
INNER JOIN Matches ON PlayersMatch.matchID = Matches.matchID
WHERE Matches.matchSeason = 35
AND Matches.matchType = 'L'
AND PlayersMatch.position IS NOT NULL
GROUP BY PlayersMatch.playerID
ORDER BY MAX(matchRating) DESC, playerForm ASC
The problem I'm getting is that while I'm getting the right playerID and player matchRating, I'm getting the wrong matchID, form, age and other info (ie they're from other records).
I tried adding the matchID to the group by, and while I got the correct information, I had duplicates as it produced duplicate records for the players (because playerID and matchID make up the PK in PlayersMatch).
Your assistance in this is greatly appreciated.
Edit: After some further reading, I must be writing the SQL incorrectly and that a group by is only going to return the correct information if I just have playerID and max(matchRating) - at the very least to be ANSI SQL correct.
In that case, how do I get the corresponding match details for that performance if I'm using a max/group by?
Edit 2: Looks like I've got a working query:
SELECT * FROM PlayersMatch
INNER JOIN
(SELECT playerID, MAX(matchRating)
FROM PlayersMatch p2
JOIN Matches
ON p2.matchID = Matches.matchID
WHERE matchSeason = 35
AND matchType = 'L'
AND p2.position IS NOT NULL
GROUP BY p2.playerID) AS p1
ON PlayersMatch.playerID = p1.playerID
AND PlayersMatch.matchRating = p1.matchRating
JOIN Matches m2
ON PlayersMatch.matchID = m2.matchID
WHERE m2.matchSeason = 35
AND m2.matchType = 'L'
AND PlayersMatch.position IS NOT NULL
ORDER BY matchRating DESC
The only problem now is that it takes 21 seconds to run. Does this query look correct?