Search code examples
database-designforeign-keysschemaprimary-keyrdbms

One foreign key referring to multiple table's primary keys


1 <1 - image> One foreign key referring to multiple table's primary keys.

<1.1> Where primary1 table has two columns primary1_id int(11) and first_name varchar(10) in which primary1_id is a primary key.

<1.2> Same as primary1 table, primary2 table has also two columns primary2_id int and last_name varchar in which primary2_id is a primary key.

<1.3>**Also there is a **foreign1 table has two columns foreign_id int and full_name int in which full_name is a foreign key which is referring to multiple table's primary keys like primary1_id and primary2_id.

2 <2 - image> This foreign key, full_name only allow to insert those values which are same in both primary1_id and primary2_id columns.

<2.1> So if I enter five entries in primary1 table and four entries in primary2.

<2.2> In which primary1_id's are set as 1 to 5 and primary2_id's are set as 1 to 4.

<2.3> But why this foreign key full_name is allowing me to enter 1 to 4 only which are available in both primary key's tables?


Solution

  • It is unusual in my experience but it potentially makes sense as a way to implement certain business rules with a meaning similar to "A must be both B and C".

    One possible example: a StaffDiscount table identifying customers who are also employees and are eligible for a discount. Such a table might have a single foreign key that references both the Customer table and the Employee table. This does assume that a common key is used to identify both customers and employees.

    CREATE TABLE StaffDiscount
     (CustomerEmployee INT NOT NULL PRIMARY KEY /* Same key identifies customer and employee */,
      FOREIGN KEY (CustomerEmployee) REFERENCES Customer (CustomerNum),
      FOREIGN KEY (CustomerEmployee) REFERENCES Employee (EmployeeNum));