"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 Tables in SQL?

Can a Foreign Key Reference Multiple Tables in SQL?

Published on 2024-11-20
Browse:258

Can a Foreign Key Reference Multiple Tables in SQL?

Polymorphic Foreign Key Constraints: A Versatile Approach

The conventional foreign key constraint establishes a direct link between two specified tables. However, what if you need a polymorphic relationship where a column refers to one of several possible parent tables?

Is a Foreign Key to Multiple Tables Possible?

Unfortunately, the answer is negative. A foreign key constraint can only reference a single parent table. This limitation arises from the need for data integrity and consistency in database systems.

Practical Considerations

Despite the inherent limitation, there are practical approaches that emulate the behavior of a foreign key to multiple tables:

  1. Union Table: Create a single union table that incorporates columns from all possible parent tables. The foreign key column in the child table references the union table. When inserting or updating data, the union table determines which actual parent table to insert or update into.
  2. Type Column: Introduce a type column in the child table to differentiate between possible parent table types. The foreign key column then references the parent table corresponding to the type specified in the type column.

Examples in MySQL and PostgreSQL

In MySQL, the following statement creates a union table:

CREATE TABLE union_table AS
SELECT * FROM subordinates
UNION ALL
SELECT * FROM products;

The foreign key constraint in the child table would then be:

ALTER TABLE images
ADD FOREIGN KEY (person_id) REFERENCES union_table(id);

In PostgreSQL, a similar approach is used:

CREATE TABLE union_table AS
SELECT * FROM subordinates
UNION ALL
SELECT * FROM products;

The foreign key constraint becomes:

ALTER TABLE images
ADD FOREIGN KEY (person_id) REFERENCES union_table(id);

Conclusion

While a direct foreign key to multiple tables is not feasible, alternative strategies allow for a polymorphic foreign key relationship in SQL database systems. These strategies preserve data integrity while providing the flexibility to accommodate multiple parent tables.

Release Statement This article is reprinted at: 1729692611 If there is any infringement, please contact [email protected] to delete it
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