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:
Examples in MySQL and PostgreSQL
In MySQL, the following statement creates a union table:
<code class="sql">CREATE TABLE union_table AS SELECT * FROM subordinates UNION ALL SELECT * FROM products;</code>
The foreign key constraint in the child table would then be:
<code class="sql">ALTER TABLE images ADD FOREIGN KEY (person_id) REFERENCES union_table(id);</code>
In PostgreSQL, a similar approach is used:
<code class="sql">CREATE TABLE union_table AS SELECT * FROM subordinates UNION ALL SELECT * FROM products;</code>
The foreign key constraint becomes:
<code class="sql">ALTER TABLE images ADD FOREIGN KEY (person_id) REFERENCES union_table(id);</code>
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.
The above is the detailed content of Can a Foreign Key Reference Multiple Tables in SQL?. For more information, please follow other related articles on the PHP Chinese website!