Foreign Key for either-or column?

后端 未结 3 1072
夕颜
夕颜 2021-01-19 14:12

Is it possible to have a foreign key that requires either column A or column B to have a value, but not both. And the foreign key for column A matches Table 1 and the forei

3条回答
  •  耶瑟儿~
    2021-01-19 14:27

    A check constraint can handle this. If this is SQL Server, something like this will work:

    create table A (Id int not null primary key)
    go
    create table B (Id int not null primary key)
    go
    create table C (Id int not null primary key, A_Id int null, B_Id int null)
    go
    alter table C add constraint FK_C_A
    foreign key (A_Id) references A (Id)
    go
    alter table C add constraint FK_C_B
    foreign key (B_Id) references B (Id)
    go
    alter table C add constraint CK_C_OneIsNotNull
    check (A_Id is not null or B_Id is not null)
    go
    alter table C add constraint CK_C_OneIsNull
    check (A_Id is null or B_Id is null)
    go
    

提交回复
热议问题