I am having trouble coming up with a workable table design for tracking head-to-head match results between users.
All users have a UID. Individual match results are stored in another table, and each match has its own UID.
What I want is to be able to pull something like this with a simple select:
Player vs. Opponent Wins Losses Draws
Bob John 5 2 1
Bob Sam 0 3 2
John Bob 2 5 1
I can pull this data out of the raw match results with some manipulation in PHP, but it’s rather costly so I’d like to use cron jobs and store these “finished” statistics in a table for quick reads.
What’s tripping me up is the fact that one data set (2 players, win, loss, draw counts) can be read in two directions, depending on which player’s point of view you want, as depicted above for Bob and John.
I could make a table like this:
[player] [opponent] [wins] [losses] [draws]
but then each “set” would require two rows…
[player] [opponent] [wins] [losses] [draws]
bob john 5 2 1
john bob 2 5 1
and that duplication seems like it might cause me problems later, though off the top of my head I can’t think of a reason why, just DRY and all that…
Suggestions?
I’ve seen the duplication approach you mention used effectively. So long as you’re aware of the duplication, it’s not too difficult to handle.
If you want to avoid the duplication, you’ll probably need more code, and more code complexity: to show all the results for a single player, you’d need to find the records where that player is either “Player” or “Opponent”.
One (I’d argue) useful way to report all the players’ records (versus their opponents) would be to display each “versus” records twice — once as a Player, grouped together, and once as an Opponent, in each of the sets of records for their opponents: