简体   繁体   中英

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. If it is a Parent comment then i would give it null for ParentId. 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. 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:

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

VERY handy!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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