【发布时间】:2019-04-23 07:38:49
【问题描述】:
在 PostgreSQL 中使用以下查询创建两个表时:
create table test_unique_pk (
id serial primary key,
value varchar not null
);
create table refer_unique_pk (
id integer,
value varchar,
foreign key (id, value) references test_unique_pk(id, value)
);
我明白了
there is no unique constraint matching given keys for referenced table "test_unique_pk".
如果我将第一个表修改为
create table test_unique_pk (
id serial primary key,
value varchar not null,
unique(id, value)
);
效果很好。
但是由于主键已经是唯一的,在我看来,复合(id, value)也应该是唯一的,因为我们不能构造两个具有相同id的元组,因此我们不能构造两个相等的@987654326元组@。
如果上面的说法是正确的,为什么PostgreSQL没有自动对包括主键在内的复合引用添加唯一约束?
【问题讨论】:
-
如果
id已经是唯一的,为什么还要将value列作为外键的一部分添加? -
因为这是他们定义语言的方式。这个问题不问设计师是无法回答的。如果您只想确认唯一列集的超集是唯一的,请编辑您的问题以提出该问题,并且您是正确的。
-
@a_horse_with_no_name,我需要保持表
test_unique_pk和表refer_unique_pk具有相同的id和value。因此数据库应该拒绝像test_unique_pk(id = 3, value="test"), refer_unique_pk(id = 3, value="other")这样的行。 -
为避免重复,
value列不应出现在refer_unique_pk或test_unique_pk表之一中。id列足以确保唯一性,因此如果您需要该值,则应通过连接获取它。
标签: database postgresql primary-key unique-constraint