5

是否有可能有一个外键要求 A 列或 B 列有一个值,但不能同时有一个值。A列的外键匹配表1,B列的外键匹配表2?

4

3 回答 3

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
于 2013-06-25T14:54:13.463 回答
2

这取决于您使用的数据库。如果您想要一个Foo与 FK 关系的表,Table1Table2一次只有一个,那么您需要设置某种触发器(我的链接假设 SQL Server,但想法相同)或约束来强制执行您的规则只有一列有值。

于 2013-06-25T14:49:18.980 回答
1

在应用外键时,列中没有必要包含值,但列名和数据类型相同。

于 2013-06-25T14:45:14.990 回答