I have two tables named players
& matches
in a Postgres DB as follows:
CREATE TABLE players (
name text NOT NULL,
id serial PRIMARY KEY
);
CREATE TABLE matches (
winner int REFERENCES players (id),
loser int REFERENCES players (id),
-- to prevent rematch btw players
CONSTRAINT unique_matches
PRIMARY KEY (winner, loser)
);
How can I ensure that only a unique combination of either (winner, loser)
or (loser, winner)
is used for matches
primary key so that the matches
table won't allow the insertion of:
INSERT INTO matches VALUES (2, 1);
If it already has a row containing VALUES (1, 2)
like :
winner | loser
--------+-------
1 | 2
The goal is to avoid entry of matches between the same players.