Foreign key constraint may cause cycles or multiple cascade paths?

后端 未结 9 1289
感情败类
感情败类 2020-11-21 23:07

I have a problem when I try to add constraints to my tables. I get the error:

Introducing FOREIGN KEY constraint \'FK74988DB24B3C886\' on table \'Empl

9条回答
  •  孤街浪徒
    2020-11-21 23:37

    A typical situation with multiple cascasing paths will be this: A master table with two details, let's say "Master" and "Detail1" and "Detail2". Both details are cascade delete. So far no problems. But what if both details have a one-to-many-relation with some other table (say "SomeOtherTable"). SomeOtherTable has a Detail1ID-column AND a Detail2ID-column.

    Master { ID, masterfields }
    
    Detail1 { ID, MasterID, detail1fields }
    
    Detail2 { ID, MasterID, detail2fields }
    
    SomeOtherTable {ID, Detail1ID, Detail2ID, someothertablefields }
    

    In other words: some of the records in SomeOtherTable are linked with Detail1-records and some of the records in SomeOtherTable are linked with Detail2 records. Even if it is guaranteed that SomeOtherTable-records never belong to both Details, it is now impossible to make SomeOhterTable's records cascade delete for both details, because there are multiple cascading paths from Master to SomeOtherTable (one via Detail1 and one via Detail2). Now you may already have understood this. Here is a possible solution:

    Master { ID, masterfields }
    
    DetailMain { ID, MasterID }
    
    Detail1 { DetailMainID, detail1fields }
    
    Detail2 { DetailMainID, detail2fields }
    
    SomeOtherTable {ID, DetailMainID, someothertablefields }
    

    All ID fields are key-fields and auto-increment. The crux lies in the DetailMainId fields of the Detail tables. These fields are both key and referential contraint. It is now possible to cascade delete everything by only deleting master-records. The downside is that for each detail1-record AND for each detail2 record, there must also be a DetailMain-record (which is actually created first to get the correct and unique id).

提交回复
热议问题