简体   繁体   English

一个外键可以引用另一个外键吗

[英]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.如果它是一个独特的领域,它也可以是另一个 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.我知道没有 DBMS 不是这种情况。 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!事实上,与公认的答案相反,引用的 FK 列甚至不必是唯一的! - at least in MySQL. - 至少在 MySQL 中。 see https://www.db-fiddle.com/f/6RUEP43vYVkyK2sxQQpBfj/0 for a demo of the same.有关相同的演示,请参见https://www.db-fiddle.com/f/6RUEP43vYVkyK2sxQQpBfj/0

which brings up the question that if the FK is not unique in the parent table, then who is the parent row?这就提出了一个问题,如果 FK 在父表中不是唯一的,那么谁是父行? The purpose of FKs is to establish parent-child relationship. FKs 的目的是建立父子关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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