[英]Unique constraint that includes serial primary key in 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,
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 一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.