Foreign key refering to multiple tables

允我心安 提交于 2020-01-24 17:03:46

问题


I have 4 tables

A(ida, name)
B(ida, B-specific stuff)
C(ida, C-specific stuff)
D(ida, D-specific stuff)

and i want that another table E could refer to just B OR C (not D). What can i write in the

CREATE TABLE E

?


回答1:


Seems to me that you are trying to use some kind of supertype/subtype -- as opposed to simple vertical partitioning. If so, do introduce a type-discriminator.

Because this is generic example (A, B, C, D ..) it is hard to guess what relates to what, so here are two options as my best guess.


Option 1


Option 2




回答2:


You could use a check constraint to enforce that D only references B or C:

create table D
    (
    id int constraint PK_D primary key,
    idb int constraint FK_D_IDB foreign key references B(id),
    idc int constraint FK_D_IDC foreign key references C(id),
    constraint CHK_D_B_OR_C check 
        (
        case when idb is null then 0 else 1 end + 
        case when idc is null then 0 else 1 end = 1
        )
    );

Live example at SQL Fiddle.



来源:https://stackoverflow.com/questions/11047391/foreign-key-refering-to-multiple-tables

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