有一个表 t 继承了 child 。我希望只有 children 才能收到插页。强制父表拒绝插入的最佳方法是什么?
create table t (c int);
create table t1 () inherits (t);
这不应该是可能的:
insert into t (c) values (1);
编辑:
除了来自@wildplasser 的解决方案之外,我还找到了一个模型可见的解决方案:
create table tfk (c integer unique check(false));
create table t (c integer, foreign key (c) references tfk(c));
现在不可能insert into t
除非它是一个空值,并且仍然可以insert into
它的 child 。如果该列已经被限制为 not null
但还不够,这可能是一个很好的解决方案。或者有人知道使上述方法适用于空值的技巧吗?
新闻:
我asked for a new syntax在 postgresql 列表中,它是为 9.2 完成的:
Allow CHECK constraints to be declared NO INHERIT (Nikhil Sontakke, Alex Hunsaker)
This makes them enforceable only on the parent table, not on child tables.
最佳答案
create table t (c int, check (false) no inherit);
这将阻止插入表 t
。它添加了一个永远不会为真的约束,因此无法插入任何数据。 no inherit
将防止该约束影响子表。
关于postgresql - 如何防止在父表中插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545783/