postgresql - 条件 PostgreSQL 外键

标签 postgresql

在 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 没有条件外键。您可能会考虑的一些选项是:

  1. 只是没有 FK 约束。将此逻辑移至数据访问层并在没有参照完整性的情况下继续存在。
  2. 在列中允许 NULL,即使有 FK 约束也是完全有效的。然后,使用另一列存储0-1的含义。
  3. 在引用表中为 0-1 添加一个虚拟行。即使它只有虚假数据,它也会满足 FK 约束。

希望这对您有所帮助!

关于postgresql - 条件 PostgreSQL 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900716/

相关文章:

json - 如何从查询中返回一个 json 数组?

c - Postgresql C函数时间戳转换

ruby-on-rails - PG::UndefinedTable:错误:使用 SELECT DISTINCT ON 时缺少表的 FROM 子句条目

oracle - 使用 Oracle GoldenGate 11.2.1 从 PostgreSQL 到 Oracle 数据库

postgresql - 如何备份 PostgreSQL 数据库并在 Digital Ocean(Ubuntu) 中找到备份数据库的位置

python - SQLAlchemy 连接如何与基于 session 的事务相关?

sql - 如何使用 Postgres 执行以下查询?

python - 从 psycopg2 中的模式获取数据

postgresql - JSP 错误 java.lang.ClassNotFoundException

postgresql - 如何在 Nginx 中使用 Postgres 和静态文件操作