What is the meaning of self referencing foreign key?

浪尽此生 提交于 2019-12-17 20:46:58

问题


I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.

ALTER TABLE [SchemaName].[TableName]  WITH CHECK ADD  
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])

What is the meaning of it?


回答1:


ALTER TABLE [SchemaName].[TableName]  WITH CHECK ADD  
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])

This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.

In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)

As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.




回答2:


In some cases this is a preferred way to reduce redundancy in your model. In using the self referencing foreign key (as shown in you example) you create a hierarchical relationship between rows in your table. Pay attention to what happens when you delete a row from the table, cascading on delete might remove rows you still want. Using these sort of keys moves some of the data validation to the DB model as opposed to making this a responsibility of the program/programmer. Some outfits prefer this way of doing things. I prefer to make sure programs and programmers are responsible - data models can be hard to refactor and upgrade in production environments.



来源:https://stackoverflow.com/questions/13330840/what-is-the-meaning-of-self-referencing-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!