You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决PostgreSQL建表报错“不存在匹配引用表给定键的唯一约束”

错误原因

你对tb_round表的主键规则理解有误:tb_round的主键是联合主键,由round_number和discipline_id两个字段共同构成,并非discipline_id单独作为主键。
外键引用的核心规则是:被引用的字段必须在父表中具备唯一约束(要么是主键,要么单独设置UNIQUE约束)。你在tb_register表中分开单独引用tb_round的discipline_id和round_number,这两个字段单独在tb_round中都没有唯一约束,因此触发报错:

there is no unique constraint matching given keys for referenced table "tb_round"

解决方法

推荐使用符合业务逻辑的联合外键方案,修改tb_register表的外键定义即可:
将你原来tb_register建表语句中分开定义的两个轮次相关外键删除:

CONSTRAINT FK_register_round_discipline  FOREIGN KEY (discipline_id) REFERENCES tb_round(discipline_id),
CONSTRAINT FK_register_round_number FOREIGN KEY (round_number) REFERENCES tb_round(round_number)

替换为一个联合外键,直接引用tb_round的完整联合主键:

CONSTRAINT FK_register_round FOREIGN KEY (round_number, discipline_id) REFERENCES tb_round(round_number, discipline_id)

修改后完整的tb_register建表语句如下:

CREATE TABLE tb_register (
    athlete_id CHARACTER(7) NOT NULL,
    round_number INT NOT NULL,
    discipline_id INT NOT NULL UNIQUE,
    register_date DATE NOT NULL DEFAULT CURRENT_DATE,
    register_position INT,
    register_time TIME,
    register_measure REAL,
    CONSTRAINT PK_tb_register PRIMARY KEY(athlete_id,round_number,discipline_id),
    CONSTRAINT FK_register_athlete  FOREIGN KEY (athlete_id) REFERENCES tb_athlete(athlete_id),
    CONSTRAINT FK_register_round FOREIGN KEY (round_number, discipline_id) REFERENCES tb_round(round_number, discipline_id)
);

修改后重新执行建表语句即可正常创建。


内容的提问来源于stack exchange,提问作者Olaola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:03