Home >Database >Mysql Tutorial >Can a Foreign Key Reference Multiple Primary Keys Simultaneously?
This example explores a common database design challenge: creating a foreign key relationship where a single table needs to reference primary keys from multiple other tables. The specific scenario involves the deductions
table needing to link to both employees_ce
and employees_sn
tables.
The question is whether a foreign key in deductions
can directly reference primary keys in both employees_ce
and employees_sn
simultaneously. The answer is: not directly, in a standard relational database. A single foreign key can only reference a single primary key.
The proposed solution leverages a well-structured inheritance model to resolve this.
The tables employees
, employees_ce
, and employees_sn
represent an inheritance hierarchy. employees
is the base table, with employees_ce
and employees_sn
as specialized tables inheriting from it.
Database Structure:
<code class="language-sql">employees (id INT PRIMARY KEY, name VARCHAR(255)) employees_ce (id INT PRIMARY KEY, ce_specific_attribute VARCHAR(255), employee_id INT, FOREIGN KEY (employee_id) REFERENCES employees(id)) employees_sn (id INT PRIMARY KEY, sn_specific_attribute VARCHAR(255), employee_id INT, FOREIGN KEY (employee_id) REFERENCES employees(id))</code>
Solution:
Instead of a direct link to both employees_ce
and employees_sn
, the deductions
table should reference the common parent table, employees
:
<code class="language-sql">deductions (id INT PRIMARY KEY, employee_id INT, deduction_amount DECIMAL(10,2), ..., FOREIGN KEY (employee_id) REFERENCES employees(id))</code>
This approach ensures referential integrity and avoids redundancy. The employee_id
in deductions
links to the employee record in employees
, regardless of whether that employee has additional information in employees_ce
or employees_sn
. This design efficiently manages the relationship and maintains data consistency.
The above is the detailed content of Can a Foreign Key Reference Multiple Primary Keys Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!