2013-06-25 19 views
2

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

回答

4

检查约束可以处理这个问题。如果这是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 
+0

谢谢!这结束了工作:) – appsecguy

1

在应用外键时,列中没有必要具有值,但列名也是相同的,也是数据类型。

+0

发布与既包括表查询......我w'll爱来解决吧.. – Viren

2

这取决于您正在使用哪个数据库。如果你想要一个具有FK关系的表FooTable1Table2但一次只有一个,那么你需要设置某种trigger(我的链接假设SQL Server,但想法是一样的)或Constraint强制您的规则只有一列有价值。