简体   繁体   中英

Can a foreign key reference another foreign key

是否可以有一个外键引用另一个表中的另一个外键,或者它只能引用主键和唯一键?

A foreign key can reference any field defined as unique. If that unique field is itself defined as a foreign key, it makes no difference. A foreign key is just to enforce referential integrity. Making a field a foreign key doesn't change the field itself in any way. If it is a unique field, it can also be the target of another FK.

For example:

create table Table1(
     PK int identity primary key,
     ...
);
create table Table2( -- 1-1 relationship with Table1
     PKFK int primary key,
     ...,
     constraint FK_Table2_1 foreign key( PKFK ) references Table1( PK )
);
create table Table3( -- relates to Table2
    PKFKFK int primary key,
    ...,
     constraint FK_Table3_2 foreign key( PKFKFK ) references Table2( PKFK )
);

I know of no DBMS where this is not the case. And I agree with Horse, there is nothing wrong with the practice.

Is it possible to have a foreign key that references another foreign key in a different table

Yes. In fact contrary to accepted answer, the referenced FK column doesn't even have to be unique! - at least in MySQL. see https://www.db-fiddle.com/f/6RUEP43vYVkyK2sxQQpBfj/0 for a demo of the same.

which brings up the question that if the FK is not unique in the parent table, then who is the parent row? The purpose of FKs is to establish parent-child relationship.

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