postgresql - 如何防止在父表中插入?

标签 postgresql database-design inheritance triggers foreign-key-relationship

有一个表 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/

相关文章:

javascript - 对所有字段进行环回搜索

javascript - Knex 迁移失败,出现错误 : The query is empty

database-design - LAMP 托管在 AWS 云上——要重写哪些 PHP 代码?

c# - 我应该/可以将 Entity Framework 用于非标准 CRUD 吗?

c++ - 多级继承和多态

c++ - 继承和存储静态类信息

postgresql - Knex 在 Postgres 中创建 POINT 数据类型

postgresql - 将一年添加到 postgresql 中的日期字段

ios - 根据项目在网格中的 x,y 位置从数据库中提取项目的最有效方法

ios - 在 Swift 中从子类访问父类属性