【发布时间】:2016-02-15 18:37:43
【问题描述】:
我在 Postgres 数据库中有两个名为 players 和 matches 的表,如下所示:
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)
);
如何确保只有 (winner, loser) 或 (loser, winner) 的唯一组合用于 matches 主键,以便 matches 表不允许插入:
INSERT INTO matches VALUES (2, 1);
如果它已经有一行包含VALUES (1, 2) 像:
winner | loser
--------+-------
1 | 2
目标是避免相同玩家之间的比赛进入。
【问题讨论】:
标签: sql postgresql database-design ddl unique-constraint