Home > Database > Mysql Tutorial > Can a Foreign Key Reference Multiple Primary Keys Simultaneously?

Can a Foreign Key Reference Multiple Primary Keys Simultaneously?

Barbara Streisand
Release: 2025-01-11 10:21:43
Original
200 people have browsed it

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))
Copy after login

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))
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template