Foreign key to one of many tables?

折月煮酒 提交于 2019-11-27 15:01:10

A foreign-key by definition must point to either a primary- or candidate- key on one-and-only-one table - primary- only is available in a typical DBMS. You're better off having a single 'person' table and have tables that are related to this with e.g. manager information.

A column is only a placeholder for a value. A foreign key constraint means that the data stored within that column can only be a value that matches the table's column defined in the constraint. Foreign key constraints are per table...

There is nothing to stop you from defining multiple foreign key constraints on a column. But this means that the only value allowed to be stored will be values that already exist in all of the other foreign related tables. IE: TABLE_1 has values 1 and 2, TABLE_2 has values 2 and 3 - TABLE_3 has foreign key relationships defined to tables 1 & 2 on TABLE_3's col column... The only valid value I can insert into TABLE_3.col is 2, because it's in both tables (assuming col is not nullable).

A foreign key can only ever point to a single table.

It looks to me like what you really wanted to do here is create a parent id in your persons table. The subordinates would have a parent id pointing at their managers. If a subordinate needed to have multiple managers a separate joining table could be created with 2 columns each containing a person id one being the subordinate and the other being one of the managers.

If you wanted to restrict who could be assigned to the parentid field this could be done with a check constraint.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!