How to keep foreign key relations consistent in a “diamond-shaped” system of relationships

前端 未结 2 2092
野性不改
野性不改 2020-12-16 22:25

Consider this situation: a Car is bought from a Salesperson. A Salesperson works at a Showroom (and at only one Showroom).

2条回答
  •  一生所求
    2020-12-16 22:55

    If I understood the question correctly, this should be close.

    enter image description here

    Here are few details for keys

    --
    -- Keys for SalesPerson
    --
    alter table SalesPerson
      add constraint PK_salesperson primary key (PersonID)
    
    , add constraint AK1_salesperson unique (ManufacturerID, ShowRoomNo, PersonID) 
    
    , add constraint FK1_salesperson foreign key (PersonID)
                               references Person (PersonID)
    
    , add constraint FK2_salesperson foreign key (ManufacturerID, ShowRoomNo)
                             references ShowRoom (ManufacturerID, ShowRoomNo)
    ;
    
    --
    -- keys for Sale table
    --
    alter table Sale
      add constraint PK_sale primary key (SaleID)
    
    , add constraint FK1_sale foreign key (BuyerID)
                        references Person (PersonID)
    
    , add constraint FK2_sale foreign key (ManufacturerID, ModelName, ShowRoomNo)
                    references CarDisplay (ManufacturerID, ModelName, ShowRoomNo)
    
    , add constraint FK3_sale foreign key (ManufacturerID, ShowRoomNo, SalesPersonID)
                   references SalesPerson (ManufacturerID, ShowRoomNo, PersonID)
    ;
    

提交回复
热议问题