繁体   English   中英

SQL Server 2 个表中的一个外键

[英]SQL Server One Foreign Key From 2 Tables

是否可以有一个可以引用 2 个不同表的外键?

这就是我的意思...

Create Table1(id nvarchar primary key);

Create Table2(id nvarchar primary key);

Create Table3(id nvarchar foreign key references (Table1(ID) or Table2(ID)) 

如果不可能,有没有推荐的方法来解决这个问题?

是的,您可以有一列(或列的元组)将多个表作为外键引用。 我 [个人] 称它们为“分叉外键”,但这只是我。

但是,这是两个单独实施的独立约束,每一个始终都是。 你不能有OR逻辑。

例如。

create Table1 (id nvarchar primary key);

create Table2 (id nvarchar primary key);

create Table3 (
  id nvarchar,
  constraint fk1 foreign key (id) references Table1 (ID),
  constraint fk2 foreign key (id) references Table2 (ID)
);

如果您需要OR条件,那么您的问题的答案是“否”。

我猜你想要对前两个表的不相交引用。

您可以非常接近持久化计算列:

Create Table1 (
    id nvarchar(255)
);

Create Table2 (
    id nvarchar(255)
);

Create Table3 (
    id nvarchar(255),
    type int not null check (type in 1, 2),
    id_1 as (case when type = 1 then id end) persisted,
    id_2 as (case when type = 2 then id end) persisted,
    foreign key (id_1) references table_1(id),
    foreign key (id_2) references table_2(id)
);

是一个 db<>fiddle。 当 id 没有正确引用指定的表时,这会显示错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM