"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 Polymorphic Associations?

Can a Foreign Key Reference Multiple Tables in Polymorphic Associations?

Published on 2024-11-16
Browse:927

Can a Foreign Key Reference Multiple Tables in Polymorphic Associations?

Polymorphic Foreign Keys: Can a Foreign Key Reference Multiple Tables?

The concept of foreign keys in relational databases typically involves specifying the exact target table that a reference column should point to. However, when dealing with polymorphic associations, where a table has a relationship with multiple other tables in a set, the question arises: is it possible to have a foreign key that can reference any one of those tables?

The Answer: No

In both MySQL and PostgreSQL, a foreign key constraint can only reference a single parent table. This constraint ensures data integrity by maintaining a clear relationship between the referencing rows and the referenced rows in the parent table.

Alternatives for Polymorphic Associations

Since a foreign key cannot directly point to multiple tables, alternative solutions are necessary to model polymorphic associations:

  • Joined Inheritance: Create a single table that contains all the columns from the child tables and a discriminator column to identify which table each row belongs to.
  • Table Per Class Hierarchy: Create separate tables for each child table and establish relationships among them through inheritance.
  • Union Types: Utilize a single column that can accommodate data values from different domains, allowing it to reference multiple child tables.

Additional Resources

For further insights into polymorphic associations and their solutions, refer to the following resources:

  • Practical Object-Oriented Models in SQL
  • SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming
Release Statement This article is reprinted at: 1729692085 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