简体   繁体   English

在同一个表的主键上创建外键约束的不良做法?

[英]Bad practice to create a foreign key constraint on primary key of the same table?

I am trying to do a comment table in my database and store the sub comments in the same table as well. 我试图在我的数据库中做一个注释表,并将子注释存储在同一个表中。 I would put a foreign key constraint on a column called "ParentId" that would be linked to the CommentId column which is the primary key of the same table. 我会在名为“ParentId”的列上放置一个外键约束,该列将链接到CommentId列,该列是同一个表的主键。 If it is a Parent comment then i would give it null for ParentId. 如果它是父评论,那么我将为ParentId赋予它null。 Is this bad practice? 这是不好的做法吗? If so what are some better ways to approach this problem. 如果是这样,有什么更好的方法来解决这个问题。

This is fine. 这可以。 One thing you'll need to consider is what to do if a comment with children is deleted. 您需要考虑的一件事是,如果删除带有子项的评论该怎么办。 The FK constraint will prevent deletions, and the common solution of cascading the delete doesn't seem appropriate here, nor does NULL-ing out the parent reference. FK约束将阻止删除,并且级联删除的常见解决方案在这里似乎不合适,也不会使父引用为NULL。 So you probably have to keep the deleted comment, and just clear out the contents or otherwise mark it as deleted. 因此,您可能必须保留已删除的注释,并清除内容或以其他方式将其标记为已删除。

it is not bad practice, but as commenters have pointed out you may run into problems later on. 这不是一种不好的做法,但正如评论者指出的那样,你可能会在以后遇到问题。

Since comments-on-comments amounts to a logical tree, it might be worth checking out Celko's work: 由于注释评论相当于逻辑树,因此可能值得查看Celko的工作:

http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html

VERY handy! 非常便利!

http://msdn.microsoft.com/en-us/library/ms124432(v=sql.100).aspx http://msdn.microsoft.com/en-us/library/ms124432(v=sql.100).aspx

For SQL Server it is not a bad practice, see above link for The Employee table definaion and refer to ManagerID column, Microsoft has used this scenario in the sample DB provided with SQL server. 对于SQL Server,这不是一个坏习惯,请参阅上面的Employee表定义链接并参考ManagerID列,Microsoft已在SQL Server提供的示例数据库中使用此方案。

The main thing need to be care of is parent record can not be deleted physically, you may need to use soft delete using flag. 需要注意的主要事情是父记录无法物理删除,您可能需要使用标记的软删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM