Adding foreign key on multiple columns

后端 未结 2 2068
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 19:10

I\'m trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error...

Here\'s what I do:

2条回答
  •  一生所求
    2021-01-11 19:28

    The problem would appear to be that you are specifying the same parent column twice in the same foreign key (i.e, (ID, ID)). The following should work:

    Create Table Test1
        (
        PK1 int not null
        , PK2 int not null
        , Primary Key ( PK1, PK2 )
        )
    
    Create Table Test2
        (
        Id int not null Auto_Increment
        , PK1 int not null
        , PK2 int not null
        , Primary Key ( ID )
        , Constraint FK_Test2
            Foreign Key ( PK1, PK2 )
            References Test1( PK1, PK2 )
        )
    

    If it is the case, that you want two columns in a child table referencing the same parent table column, then you must add two foreign key references as shown by rsenna as those represent two independent relations.

提交回复
热议问题