简体   繁体   English

复合主键+外键

[英]Composite Primary Key + Foreign Key

I have a table which contains a list of Surveys (PK is ID) 我有一个包含调查列表的表(PK是ID)

CREATE TABLE [dbo].[SurveyMaster](
    [ID] [nvarchar](4) NOT NULL,
    [Title] [nvarchar](200) NULL,
    [IsActive] [bit] NOT NULL,

And a table which contains a list of Variable Mappings. 还有一个包含Variable Mappings列表的表。

CREATE TABLE [dbo].[VariableMappings](
    [ParentSurvey_ID] [nvarchar](4) NOT NULL,
    [ReportingMonth] [nvarchar](6) NOT NULL,
    [VariableName] [nvarchar](400) NOT NULL,
    [Value] [int] NOT NULL

My hope was to create a primary key for VariableMappings on ParentSurvey_ID, ReportingMonth and Variable Name to ensure a unique record. 我希望在ParentSurvey_ID,ReportingMonth和Variable Name上为VariableMappings创建一个主键,以确保唯一的记录。

At the same time though, I'd like a foreign key relationship between VariableMappings.ParentSurvey_ID and SurveyMaster.ID to ensure VariableMappings only contains relevant SurveyID's. 但与此同时,我希望VariableMappings.ParentSurvey_ID和SurveyMaster.ID之间存在外键关系,以确保VariableMappings仅包含相关的SurveyID。

I've tried a couple of approaches in SQL Server but I don't believe I can create the FK due to the composite key being made up of 3 columns. 我在SQL Server中尝试了几种方法但我不相信我可以创建FK,因为复合键由3列组成。

How can I go about achieving this? 我怎样才能实现这一目标?

Yes, you can: 是的你可以:

CREATE TABLE [dbo].[VariableMappings](
    [ParentSurvey_ID] [nvarchar](4) NOT NULL,
    [ReportingMonth] [nvarchar](6) NOT NULL,
    [VariableName] [nvarchar](400) NOT NULL,
    [Value] [int] NOT NULL,
  PRIMARY KEY (ParentSurvey_ID, ReportingMonth, VariableName),
  FOREIGN KEY (ParentSurvey_ID)
    REFERENCES dbo.SurveyMaster (ID)
) ;

Mostly irrelevant to your problem, but having a PRIMARY KEY that is so wide (410 nvarchars) is not the best idea. 大多与你的问题无关,但拥有一个如此宽的PRIMARY KEY (410个nvarchars)并不是最好的主意。

Your primary key definition and foreign key definitions are orthogonal. 您的主键定义和外键定义是正交的。 You can declare your composite primary key and your single column foreign key without issue. 您可以毫无问题地声明复合主键和单列外键。 I would suggest to you, though, that a surrogate primary key on VariableMappings is better choice vs. the composite key - specifically for foreign keys pointing at VariableMappings . 不过,我建议你, VariableMappings上的代理主键是复合键的更好选择 - 特别是对于指向VariableMappings外键。

There is one primary key that does matter and it is that of SurveyMaster . 有一个主键很重要,它是SurveyMaster主键。 As long as ID is the primary key there, you can reference it from any number of other tables, regardless of those tables' primary keys. 只要ID是主键,就可以从任意数量的其他表中引用它,而不管这些表的主键是什么。

A foreign key requires that the referenced combination of columns is unique, and the uniqueness must be guaranteed, for example by a primary key constraint. 外键要求引用的列组合是唯一的,并且必须保证唯一性,例如通过主键约束。

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

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