Sql server 引用技术密钥的外键

Sql server 引用技术密钥的外键,sql-server,Sql Server,因此,我创建了一个表,如下所示: create table CharacterSavingThrow ( CharacterCode int not null, constraint FK_CharacterSavingThrowCharacterID foreign key (CharacterCode) references Character(CharacterCode), FortitudeSaveCode int not null, constraint

因此,我创建了一个表,如下所示:

create table CharacterSavingThrow
(
    CharacterCode int not null,
    constraint FK_CharacterSavingThrowCharacterID foreign key (CharacterCode) references Character(CharacterCode),
    FortitudeSaveCode int not null,
    constraint FK_CharacterSavingThrowFortitudeSaveCode foreign key (FortitudeSaveCode) references SavingThrow(SavingThrowCode),
    ReflexSaveCode int not null,
    constraint FK_CharacterSavingThrowReflexSaveCode foreign key (ReflexSaveCode) references SavingThrow(SavingThrowCode),
    WillSaveCode int not null,
    constraint FK_CharacterSavingThrowWillSaveCode foreign key (WillSaveCode) references SavingThrow(SavingThrowCode),
    constraint PK_CharacterSavingThrow primary key clustered (CharacterCode, FortitudeSaveCode, ReflexSaveCode, WilSaveCode)

)

我需要知道如何从另一个表的约束引用该表的主键?这似乎是个很简单的问题,要么可能,要么不可能,对吧?谢谢你们的帮助

是-非常简单-您只需指定完整的复合索引,例如,您的另一个表也需要有构成PK的这四列,然后FK约束将是:

ALTER TABLE dbo.YourOtherTable
ADD CONSTRAINT FK_YourOtherTable_CharacterSavingThrow
FOREIGN KEY(CharacterCode, FortitudeSaveCode, ReflexSaveCode, WilSaveCode)
REFERENCES dbo.CharacterSavingThrow(CharacterCode, FortitudeSaveCode, ReflexSaveCode, WilSaveCode)
要点是:如果您有一个复合主键(由多个列组成),则要引用该表的任何其他表也必须具有所有这些列,并将所有这些列用于FK关系

此外,如果您正在编写将连接这两个表的查询,那么您必须使用复合PK中包含的所有列进行连接


这是使用四列作为主键的主要缺点之一——它使FK关系和连接查询非常繁琐,编写和使用起来非常烦人。因此,在这种情况下,我可能会选择在表中使用一个单独的代理键-例如,在
dbo.CharacterSavingThrow
表中引入一个新的
INT-IDENTITY
,作为主键,这将使引用该表和编写使用该表的联接查询变得更加容易。

是-非常简单-您只需指定完整的复合索引,例如,您的另一个表也需要有构成PK的这四列,然后FK约束将是:

ALTER TABLE dbo.YourOtherTable
ADD CONSTRAINT FK_YourOtherTable_CharacterSavingThrow
FOREIGN KEY(CharacterCode, FortitudeSaveCode, ReflexSaveCode, WilSaveCode)
REFERENCES dbo.CharacterSavingThrow(CharacterCode, FortitudeSaveCode, ReflexSaveCode, WilSaveCode)
要点是:如果您有一个复合主键(由多个列组成),则要引用该表的任何其他表也必须具有所有这些列,并将所有这些列用于FK关系

此外,如果您正在编写将连接这两个表的查询,那么您必须使用复合PK中包含的所有列进行连接


这是使用四列作为主键的主要缺点之一——它使FK关系和连接查询非常繁琐,编写和使用起来非常烦人。因此,在这种情况下,我可能会选择在表中使用一个单独的代理键-例如,在
dbo.CharacterSavingThrow
表中引入一个新的
INT-IDENTITY
,作为主键,这将使引用该表并编写使用该表的联接查询变得更加容易。

哈哈,好吧。谢谢!我想我可能会使用一个代理键…我的SQL老师会适合这个=哈哈,好吧。谢谢!我想我可能会使用一个代理键…我的SQL老师会适合这个=D