是否可以使用Cascade Delete功能,是可用的外键
是否可以声明用作外键但可能为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经正确执行了。如果外键列为null,则该行不会执行参考完整性。
You are already doing it correctly. If the foreign key column is NULL, referential integrity is not enforced for that row.
这是可能的。只需检查以下线程:
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:
PostgreSQL: NULL value in foreign key column
Can foreign key references contain NULL values in PostgreSQL?
The cascade deletion should also work, because at the end the column is a valid reference.