繁体   English   中英

使用外键从表中的几列引用另一个表?

[英]Refer from several columns in table to single another table using foreign keys?

我在 SQL Server 中有一个表,它有 5 列,我想使用外键引用另一个表的行。

问题:一行是否可能通过外键引用另一个表的相同或不同行? 如果是,我如何在 MSSQL 中声明它。 是否应该向外键添加任何特殊选项,以便在更新或删除第一个表的行时不会产生任何错误?

例子:

 Table 2: 

 Id Value1 Value2  Value3
 1  aaa    bbb     ccc
 2  ddd    eee     fff
 3  aaa    bbb     ccc
 ...


  Table 1:

 Id Column1=FK to table2  Column2=FK to table2 Column3=FK to table2
 1  1                     1                    3
 2  3                     2                    1

etc.

这并不比单个外键更复杂。 它有一种明确的气味,即设计不太理想。 但是如果不了解业务需求,就不可能确定或帮助找到更好的架构。

这是您的问题中概述的一个工作示例。

create table Table2
(
    Id int identity primary key
    , Value1 varchar(10)
)

create table Table1
(
    Id int identity primary key
    , Val1 int 
    , Val2 int
    , Val3 int
    , constraint FK_Table1_Table2_Val1 foreign key (Val1) references Table2(Id)
    , constraint FK_Table1_Table2_Val2 foreign key (Val2) references Table2(Id)
    , constraint FK_Table1_Table2_Val3 foreign key (Val3) references Table2(Id)
)

insert Table2 values
('first val')
, ('second')
, ('third')

insert Table1 values
(1, 1, 3)
, (3, 2, 1)

暂无
暂无

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

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