Background:
I want to create a database that can run a tournament of 1 vs 1 matchups. It needs to keep track of who won and lost each matchup and any comments about that matchup as well as decide the next unique matchup randomly.
Rules:
There are x number of players. Each player will eventually play every other player once, in effect covering all possible unique combinations of players.
Database Tables (with Sample data):
DECLARE @Players TABLE (
ID INT PRIMARY KEY IDENTITY,
Name VARCHAR(50)
)
ID Name
-- -----
1 Alex
2 Bob
3 Chris
4 Dave
DECLARE @Matches TABLE (
ID INT PRIMARY KEY IDENTITY,
WinnerId INT,
LoserId INT
)
ID WinnerId LoserId
-- -------- -------
1 1 2
2 4 2
3 3 1
DECLARE @Comments TABLE (
ID INT PRIMARY KEY IDENTITY,
MatchId INT,
Comment VARCHAR(MAX)
)
ID MatchId Comment
-- ------- ------------------------------
1 2 That was a close one.
2 3 I did not expect that outcome.
Problem:
- How can I efficiently query to get a single random match up that has not yet occurred?
The major problem is that the number of player can and will grow over time. Right now in my example data I only have 4 players which leaves 6 possible matches.
Alex,Bob
Alex,Chris
Alex,Dave
Bob,Chris
Bob,Dave
Chris,Dave
That would be small enough to simply keep grabbing 2 random numbers that correspond to the Player’s id and then check the matchups table if that matchup has already occurred. If it has: get 2 more and repeat the process. If it hasn’t then use it as the next matchup. However if I have 10,000 players that would be 49995000 possible matchups and it would simply become too slow.
Can anyone point me in the right direction for a more efficient query? I am open to changes in the database design if that would help make things more efficient as well.
If you make an outer join between every possible pairing and those that have been played, then filter out the ones that have been played, you’re left with pairings that have not yet been played. Selecting a random one is then a trivial case of ordering:
EDIT
As noted by ypercube below, the above
LIMITsyntax is MySQL specific. You may need to use instead the appropriate syntax for your SQL implementation – let us know what it is and someone can advise, if required. I know that in Microsoft SQL Server one usesTOPand in OracleROWNUM, but otherwise your Googling is probably as good as mine. 🙂