Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign Key for either-or column?

Tags:

sql

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 foreign key for column B matches Table 2?

like image 806
appsecguy Avatar asked Jun 25 '13 14:06

appsecguy


People also ask

Can two columns be a foreign key?

(Note: foreign keys can be composite keys, so the foreign key for one column could be two or more columns in another table.

Does the foreign key go on the one or many side?

The foreign key is the anchor on the many side of a one-to-many (1:M) relationship, much as the primary or candidate key is the anchor on the one side of this relationship.

How do you decide where to put foreign key?

When you join the two tables together, the primary key of the parent table will be set equal to the foreign key of the child table. Whichever one is not the primary key is the foreign key. In one-to-many relationships, the FK goes on the "many" side.


1 Answers

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
like image 73
Joe Enos Avatar answered Oct 15 '22 13:10

Joe Enos