在postgresql中包含串行主键的唯一约束

在postgresql中包含串行主键的唯一约束,postgresql,Postgresql,我有一个布局如下的postgresql表: create table bar( bar_id serial primary key, ... other columns ) create table foo( foo_id serial primary key, bar_id bigint not null, ... other columns ) create table baz( baz_id serial primary key, f

我有一个布局如下的postgresql表:

create table bar(
    bar_id serial primary key,
    ... other columns
)
create table foo(
    foo_id serial primary key,
    bar_id bigint not null,
    ... other columns
)
create table baz(
    baz_id serial primary key,
    foo_id bigint not null references foo(foo_id),
    bar_id bigint not null references bar(bar_id),
    constraint fk_fb foreign key (foo_id, bar_id) references foo(foo_id, bar_id)
)
我想在另一个表(baz)中同时引用foo_id和bar_id,并有一个外键约束,因此我需要向(foo_id,bar_id)添加一个唯一约束。foo_id是主键这一事实保证了foo_id和bar_id的组合是唯一的,即使bar_id的每个值都是相同的。我的问题是,在(foo_id,bar_id)上添加唯一约束是否会影响性能,或者postgresql是否足够聪明,知道foo_id作为主键在整个表中是唯一的,这意味着不需要对bar_id执行任何操作


表foo包含baz中不存在的行,因此从foo表中删除bar_id将不起作用。

添加另一个
UNIQUE
约束会导致性能下降,因为这样的约束是通过索引实现的,该索引需要为表上的每次数据修改而更新

一个事情,你可以考虑,如果这个表上的DML性能是溢价是在两列定义主键。然后您将失去

foo_id
的唯一性保证,但您不必为额外的索引付出代价


也许您还可以提出一种替代数据模型,它不需要您使用外键引用两列,就像GMB在其回答中建议的那样。

我想在另一个表中同时引用foo_id和bar_id:为什么?序列列足以唯一标识
foo
表中的一行。@GMB是否可以使
上的更新级联保持
foo
baz
同步?(并不是说这是个好主意)“从foo表中删除bar_id不起作用。”-但是从
baz
表中删除
bar_id
列怎么样?以及制作
foo.bar\u id
参考
bar