"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can a Foreign Key Reference Multiple Primary Keys Simultaneously?

Can a Foreign Key Reference Multiple Primary Keys Simultaneously?

Posted on 2025-03-22
Browse:593

Can a Foreign Key Reference Multiple Primary Keys Simultaneously?

Handling Complex Foreign Key Relationships in Database Design

Scenario

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 Problem and its Solution

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.

Inheritance-Based Approach

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:

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))

Solution:

Instead of a direct link to both employees_ce and employees_sn, the deductions table should reference the common parent table, employees:

deductions (id INT PRIMARY KEY, employee_id INT, deduction_amount DECIMAL(10,2), ..., FOREIGN KEY (employee_id) REFERENCES employees(id))

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3