PostgreSQL中的外键+表继承?

问题描述 投票:17回答:2

我有三张桌子:organizationorganization_teamsorg_users。这里organization_teams继承自organization。因此,假设如果在organizations_teams中添加记录,它将获得organizationid作为idorganization_teams列的值。

org_usersidorganization列上有外键。现在,当我尝试在org_users中插入数据时,它给出了如下错误

insert or update on table "org_users" violates foreign key constraint "org_users_organizations"
DETAIL:  Key (org_id)=(12) is not present in table "organizations"

为什么?

postgresql inheritance
2个回答
27
投票

这是covered in the user manual

简短版本:您可以使用外键或表继承,但不能同时使用两者。这本身并不是不可能的,只是技术上很难以快速,可靠的方式实现跨PostgreSQL中的继承表的唯一索引。没有它,你就没有有用的外键。没有人能够成功实现它,因为补丁添加支持已经被PostgreSQL接受了。

外键可以指向作为继承层次结构的一部分的表,但它只能在该表中准确找到行。不在任何父表或子表中。要查看外键看到的行,请执行SELECT * FROM ONLY thetableONLY关键字表示“忽略继承”,这就是外键查找将执行的操作。


0
投票

我发现的唯一解决方法是:

  1. create函数返回触发器,用于检查继承表中是否存在某个id
  2. 创建约束触发器而不是FK
© www.soinside.com 2019 - 2024. All rights reserved.