我有三张桌子:organization
,organization_teams
和org_users
。这里organization_teams
继承自organization
。因此,假设如果在organizations_teams
中添加记录,它将获得organization
表id
作为id
中organization_teams
列的值。
org_users
在id
的organization
列上有外键。现在,当我尝试在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中的继承表的唯一索引。没有它,你就没有有用的外键。没有人能够成功实现它,因为补丁添加支持已经被PostgreSQL接受了。
外键可以指向作为继承层次结构的一部分的表,但它只能在该表中准确找到行。不在任何父表或子表中。要查看外键看到的行,请执行SELECT * FROM ONLY thetable
。 ONLY
关键字表示“忽略继承”,这就是外键查找将执行的操作。
我发现的唯一解决方法是: