Foreign key in composite primary key

2019-08-11 14:13发布

问题:

I have the following 3 tables:

tblA

ID - PK
name

tblB

ID - PK
tblAID - FK references tblA.ID
pkID2

tblC

ID - PK
tblAID *
fkID2 *
...

I want to make this tuple a FK of (tblB.tblAID, tblB.pkID2)

If I do this:

alter table tblC with check 
add constraint FK_tblC_tblB 
foreign key (tblAID, fkID2) 
references tblB (tblAID, pkID2)

I get an error message:

There are no primary or candidate keys in the referenced table 'tblB' that match the referencing column list in the foreign key 'FK_tblC_tblB'

I.e.: I want to ensure that the tuple pair inserted into tblC exists in tblB. But I cannot do that as pkID2 is not a key. Really tblB could have tblAID, pkID2 as a composite primary key. But then tblAID would still have to be a FK of tblA.ID.

回答1:

Really tblB could have tblAID, pkID2 as a composite primary key.

Or create a new unique key from these two fields. A foreign key does not need to refer to a primary key.

But then tblAID would still have to be a FK of tblA.ID.

That will still work. A column in a primary or unique key can also participate in other constraints, including foreign key constraints.