how should data integrity be maintained in a situation where a foreign key relationship could be deleted

StackOverflow https://stackoverflow.com/questions/9847302

문제

Let's say I have a table of PlantGroups. They are dependent on the table Plants and have the foreign key PlantId. Each PlantGroup only contains one Plant.

PlantGroups
==========
...data...
PlantId

Plants
======
PlantId

If the record in the table Plants is deleted, or is requested to be deleted, what process should be taken to ensure the data integrity of PlantGroups?

Moreover, what if other data in the corresponding PlantGroups record (that was dependent on the Plants record which was requested for deletion) is still relevant and worth keeping?

도움이 되었습니까?

해결책 2

I am going to go with Option Other. Although not defined in any Data Integrity guides I have read, including Oracles (who only lists NULL, CASCADE, RESTRICT, NO ACTION, DEFAULT as options), I am going to roll my own.

Here is what is going to happen unless someone else convinces me of a better approach.

PlantGroups
===========
... data  ...
PlantId

Plant
=====
PlantId
bool isActive

On delete of Plant isActive will be set to false. This will cause a lot of extra logic to be included in the management of the database but will allow for a shallow delete of these dependent fields. A cascade delete option will perhaps sit as a final option somewhere to deal with deprecated data which is over a certain amount of years old.

Alternatively

I could also have a second database which was the same schema as the first and held deleted data.

다른 팁

Off the bat, if PlantGroups can have more than one Plant, you should have an extra table that has PlantGroupID and PlantID.

Depending on what you are trying to accomplish, you may want to have logic that will delete a PlantGroup if it has no Plants. However, it would probably be easier to add logic that will ignore blank groups in some situations such as looking them up but show them when people need to add plants to a group.

For your other questions, you should look into cascading deletes. Someone else might be able to provide more information on that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top