非此即彼列的外键?

app*_*guy 5 sql

是否有可能有一个外键要求 A 列或 B 列有一个值,但不能两者都具有值。A 列的外键与表 1 匹配,B 列的外键与表 2 匹配?

Joe*_*nos 5

检查约束可以处理这个问题。如果这是 SQL Server,则类似以下内容可以工作:

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
Run Code Online (Sandbox Code Playgroud)