是否可以使用Cascade Delete功能,是可用的外键

发布于 2025-01-31 17:43:01 字数 556 浏览 1 评论 0原文

是否可以声明用作外键但可能为null的表列?

我有一个表消息,其中包含user_uuid作为对user_profiles表的外键参考。

SELECT * FROM messages;

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

我想为广播消息允许nulls,但是如果指定了User_uuid,我想确保使用USER_PROFILE表验证它,并在用户删除时执行用户消息的级联删除。 是否有一种方法可以通过数据库手段来做到这一点?

ps我知道制作0000000-0000-0000-0000-0000000000的解决方案,桌子中的伪造记录并引用它。但是有更多文明的方式吗?

Is it possible to declare table column that is used as foreign key, but can be null?

I have a table messages that contains user_uuid as foreign key reference to user_profiles table.

SELECT * FROM messages;

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

I want to allow nulls for broadcast messages, but if user_uuid is specified, i want to make sure it is validated against user_profile table, and also to perform cascade deletion of user messages in case when user gets deleted.
Is there a way to do so by just database means?

p.s. I know the solution of making 0000000-0000-0000-0000-0000000000 fake record in a table and referencing it. But is there more civilized way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回忆那么伤 2025-02-07 17:43:01

您已经正确执行了。如果外键列为null,则该行不会执行参考完整性。

You are already doing it correctly. If the foreign key column is NULL, referential integrity is not enforced for that row.

仅冇旳回忆 2025-02-07 17:43:01

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

  • postgresql:efirtic键


  • =“ https://stackoverflow.com/questions/28206232/28206232/can-foreign-key-references-contain-null-values-in-postgresql”>可以外键参考可以包含null值吗?

级联删除也应起作用,因为最后列是有效的参考。

This is possible. Just check following threads:

The cascade deletion should also work, because at the end the column is a valid reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文