如何防止在父表中插入?

Clo*_*eto 9 postgresql inheritance triggers database-design foreign-key-relationship

有一个表t继承了孩子.我希望只有孩子才能收到插页.强制父表拒绝插入的最佳方法是什么?

create table t (c int);
create table t1 () inherits (t);
Run Code Online (Sandbox Code Playgroud)

这不应该是可能的:

insert into t (c) values (1);
Run Code Online (Sandbox Code Playgroud)

编辑:

除了@wildplasser之外,我找到了一个模型可见的解决方案:

create table tfk (c integer unique check(false));
create table t (c integer, foreign key (c) references tfk(c));
Run Code Online (Sandbox Code Playgroud)

现在它是不可能的,insert into t除非它是一个空值,并且仍然可以为insert into它的孩子.如果该列已经被约束,那么它可以是一个很好的解决方案,否则就not null不够了.或者有人知道一个技巧,使上述工作为空值?

新闻:

我在postgresql列表中要求一个新的语法,它已经完成了9.2:

允许CHECK约束被声明为NO INHERIT(Nikhil Sontakke,Alex Hunsaker)

这使得它们只能在父表上强制执行,而不能在子表上强制执行.

Joe*_*Dyk 5

create table t (c int, check (false) no inherit);
Run Code Online (Sandbox Code Playgroud)

这样可以防止插入表格t.它添加了一个永远不会成立的约束,因此不能插入任何数据.no inherit将阻止该约束影响子表.


Eel*_*lke 4

您可以使用插入前触发器来引发错误或重定向到正确的表。