表 A 上的表 A 的外键
我有一个包含用户的表
users
+------+
- user_id
...
...
- updated_by
,据我所知,updated_by
列应该在 user_id
列上引用该表。我不确定这是否正确,但我没有看到任何其他方法。我的数据库使用3NF。
谢谢大家的帮助和建议。
I have a table with users
users
+------+
- user_id
...
...
- updated_by
as I understand column updated_by
should reference this table on column user_id
. I'm not sure, that this would be correct, but I don't see any other way. My database uses 3NF.
Thank you all for help and suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,如果表适合您的使用,那么让表具有与其自身的外键关系是完全适当和正确的。
Yes, it's entirely appropriate and correct to have a table have a foreign key relationship back to itself, if that's what's appropriate for your usage.
这没有什么问题,它只是一个自引用的“外”键。问题在于准备数据库 - 在应用外键之前表中必须有根记录,或者在将新根记录插入到空表中时必须有某种方法禁用外键检查。
另一个危险是错误应用级联更新或删除。如果您在链的错误一端启动它,则可能会意外擦除/更新表的大块。例如......您删除根节点,并且删除会级联到所有子记录。
There's nothing wrong with this, it's just a self-referential "foreign" key. The problem is priming the database - there has to be either a root record in the table before you apply the foreign key, or there has to be some way of disabling the foreign key checks when inserting new root records into an otherwise empty table.
The other danger is a mis-applied cascading update or delete. If you start it at the wrong end of the chain, you could wipe out/update large chunks of the table by accident. e.g... you delete the root node, and the delete cascades itself down to all child records.
是的,这很常见。这就是(通常?)父/子关系的实现方式。
另一种选择(如果您想避免在
updated_by
字段中出现一个或多个带有NULL
的"root"
记录),就是移动updated_by
到第二个表,其中user_id
和updated_by
都引用user.user_id
:Yes, this is very common. It's how (usually?) parent/child relationships are implemented.
Another option (if you want to avoid having one or more
"root"
records withNULL
in theupdated_by
fields), is to moveupdated_by
to a second table where bothuser_id
andupdated_by
referenceusers.user_id
: