I have a table of players and I'm trying to create an SQL query to link them in order to assign matches for a specific round. Each player has an account, and I want to combine players who have similar points. I do not want any player to appear in more than one pair.
To start, I created the following view:
CREATE VIEW all_possible_pairs AS SELECT p1.id AS player1, p2.id AS player2 FROM players as p1, players as p2 WHERE p1.id < p2.id ORDER BY ABS(p1.score - p2.score)
all_possible_pairs receives all possible pairs of players and avoids the coincidence of players with itself and includes the same pair twice (for example, a, bb, a). The data is ordered in the way that I want the pairs that appear first are preferred for the pairs that appear later (since they have closer estimates).
I want to select lines from all_possible_pairs where the player first appears. In the resulting table, each player should appear only once after two columns (for example, if a player first appears in player2, they should not appear in player1 or player2 in any subsequent lines).
So, suppose players a, b, c, d and all_possible_players look like this:
player1, player2 ab ac ad bc bd cd
I want to choose from this view to get the following:
player1, player2 ab cd
I banged my head against the wall for several seconds, trying to use the various SELECT DISTINCT clauses, but I cannot figure out what is right. For example, the SELECT DISTINCT on player1 in the above example will contain b, c, which is not what I want, since it means that b and c are in the table twice.