检查约束可以解决这个问题。如果这是SQL Server,则将执行以下操作:
create table A (Id int not null primary key)gocreate table B (Id int not null primary key)gocreate table C (Id int not null primary key, A_Id int null, B_Id int null)goalter table C add constraint FK_C_Aforeign key (A_Id) references A (Id)goalter table C add constraint FK_C_Bforeign key (B_Id) references B (Id)goalter table C add constraint CK_C_oneIsNotNullcheck (A_Id is not null or B_Id is not null)goalter table C add constraint CK_C_oneIsNullcheck (A_Id is null or B_Id is null)go



