Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a foreign key reference another foreign key

Is it possible to have a foreign key that references another foreign key in a different table, or can it only reference primary and unique keys?

like image 970
joshcunningsworth Avatar asked Apr 09 '15 01:04

joshcunningsworth


People also ask

Can you link 2 foreign keys?

In a word, yes. You can have as many foreign keys as you want referencing the same primary key. The recommended limit for the number of foreign keys in a table is 253.

Can a foreign key reference non primary key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.

Can a foreign key reference any column?

Foreign key columns must use their referenced column's type. A foreign key column cannot be a virtual computed column, but it can be a stored computed column. A single column can have multiple foreign key constraints.


1 Answers

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.

like image 65
TommCatt Avatar answered Oct 16 '22 05:10

TommCatt