具有级联删除功能的postgresql可空外键是否可能

is postgresql nullable foreign key with cascade delete feature possible

是否可以声明用作外键但可以为空的 table 列?

我有 table 条消息,其中包含 user_uuid 作为对 user_profiles table.

的外键引用
SELECT * FROM messages;

id   user_uuid                              message
--   ---------                              -------
 1   f52acab5-6115-4a09-ad81-eac662292968   Hello user john smith
 2   null                                   Hello all

我想允许广播消息为空值,但是如果指定了 user_uuid,我想确保它针对 user_profile table 进行了验证,并且还要执行级联删除用户消息的数量,以防用户被删除。 有没有办法只通过数据库的方式来做到这一点?

p.s。我知道在 table 中制作 0000000-0000-0000-0000-0000000000 假记录并引用它的解决方案。但是还有更文明的方式吗?

你已经做对了。如果外键列为 NULL,则不会对该行强制执行参照完整性。

这是可能的。只需检查以下线程:

  • PostgreSQL: NULL value in foreign key column

级联删除也应该有效,因为最后该列是有效引用。