在 PostgreSQL 中是否可以有条件地添加外键?
类似于:ALTER TABLE table1 ADD FOREIGN KEY (some_id) REFERENCES other_table WHERE some_id NOT IN (0,-1) AND some_id IS NOT NULL;
具体来说,我的引用表包含所有正整数 (1+),但我需要添加外键的表可以包含零 (0)、空值和负一 (-1),所有含义都不同。
注意事项:
I am fully aware that this is poor table design, but it was a clever trick built 10+ years ago when the features and resources we have available at this point did not exist. This system is running hundreds of retail stores so going back and changing the method at this point could take months which we don't have.
I can not use a trigger, this MUST be done with a foreign key.
最佳答案
简短的回答是否定的,Postgres 没有条件外键。您可能会考虑的一些选项是:
- 只是没有 FK 约束。将此逻辑移至数据访问层并在没有参照完整性的情况下继续存在。
- 在列中允许
NULL
,即使有 FK 约束也是完全有效的。然后,使用另一列存储0
和-1
的含义。 - 在引用表中为
0
和-1
添加一个虚拟行。即使它只有虚假数据,它也会满足 FK 约束。
希望这对您有所帮助!
关于postgresql - 条件 PostgreSQL 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900716/