Foreign key in composite primary key

China☆狼群 提交于 2020-01-05 11:47:10

问题


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.



来源:https://stackoverflow.com/questions/8733548/foreign-key-in-composite-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!