What is the meaning of self referencing foreign key?

后端 未结 2 1442
情深已故
情深已故 2020-12-11 06:05

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 TA         


        
2条回答
  •  被撕碎了的回忆
    2020-12-11 06:27

    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.

提交回复
热议问题