"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 a Relational Database?

Can a Foreign Key Reference Multiple Tables in a Relational Database?

Published on 2024-11-09
Browse:407

Can a Foreign Key Reference Multiple Tables in a Relational Database?

Can a Foreign Key Point to Multiple Tables?

Setting foreign key constraints typically involves selecting a single target table. However, in the context of polymorphic relationships, a single table may have connections with multiple other tables.

Polymorphic Relationships and Foreign Keys

In polymorphic relationships, a table (e.g., images) maintains a relationship with one of several other tables (e.g., subordinates or products). This is achieved through a column (person_type) that identifies the specific table to which the foreign key should point.

Answer

Unfortunately, no. Foreign key constraints only allow references to a single parent table. This means that you cannot create a foreign key that points to multiple tables simultaneously.

Alternatives

However, there are ways to simulate this behavior using other techniques, such as:

  • Discriminator columns: Add a column to the parent table that identifies the type of child table.
  • Union tables: Create a single table that contains the combined data from all related tables.
Release Statement This article is reproduced at: 1729692950 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