简体   繁体   中英

Foreign key in composite primary key

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'

Ie: 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM