外键指的多个表(Foreign key refering to multiple tables)

2019-09-18 03:49发布

有我4桌

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

我想另一个表E可能是指只B或C(不d)。 我可以写什么的

CREATE TABLE E

Answer 1:

在我看来,你试图使用某种超/亚型的 - 而不是简单的垂直分区。 如果是这样,引入类型鉴别。

因为这是通用的例子(A,B,C,d ..)这是很难猜测关于什么,所以这里有两个选项,我最好的猜测。


选项1


选项2



Answer 2:

你可以使用一个check约束来强制执行D只引用BC

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
        )
    );

在SQL小提琴活生生的例子。



文章来源: Foreign key refering to multiple tables