创建外键以复合主键

时间:2017-08-20 12:26:26

标签: sql sql-server database tsql azure-sql-server

我有两张桌子 - 教育工作者学院

CREATE TABLE [dbo].[Educators]
(
    [UserId] [nvarchar](128) NOT NULL,
    [FacultyId] [smallint] NOT NULL,
    [InstitutionUserId] [nvarchar](128) NOT NULL,

    CONSTRAINT [PK_Educators] 
        PRIMARY KEY CLUSTERED ([UserId] ASC)
)

CREATE TABLE [dbo].[Faculties]
(
    [InstitutionUserId] [nvarchar](128) NOT NULL,
    [FacultyId] [smallint] NOT NULL,

    CONSTRAINT [PK_UserFaculties] 
        PRIMARY KEY CLUSTERED ([InstitutionUserId] ASC, [FacultyId] ASC)
)

Faculties的复合主键由两列(InstitutionUserIdFacultyId组成)组成。我在Educators表中也有相同的列。我想用外键将这两个表链接在一起。

所以,这是我的问题:

ALTER TABLE [dbo].[Educators] WITH CHECK 
    ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] 
    FOREIGN KEY ([FacultyId], [InstitutionUserId])
    REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])

但我收到此错误消息:

  

Ms 1776,Level 16,State 0,Line 7
  引用的表'dbo.Faculties'中没有主键或候选键与外键'FK_Educators_FacultyId_Faculties_FacultyId'中的引用列列表匹配。

     

Msg 1750,Level 16,State 1,Line 7
  无法创建约束或索引。查看以前的错误。

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你的桌子和他们的约束看起来很好。我能看到的唯一问题是主键中列的顺序

CONSTRAINT [PK_UserFaculties] PRIMARY KEY CLUSTERED 
(
    [InstitutionUserId] ASC,
    [FacultyId] ASC
)

与您在外键约束中声明的顺序不同

ALTER TABLE [dbo].[Educators]  WITH CHECK ADD  CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([FacultyId], [InstitutionUserId])
REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])

尝试更改外键声明中列的顺序,如下所示:

ALTER TABLE [dbo].[Educators]  WITH CHECK ADD  CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([InstitutionUserId], [FacultyId])
REFERENCES [dbo].[Faculties] ([InstitutionUserId], [FacultyId])

答案 1 :(得分:1)

密钥的顺序应与它们的定义相同:

ALTER TABLE dbo.Educators
    ADD CONSTRAINT FK_Educators_FacultyId_Faculties_FacultyId
        FOREIGN KEY(InstitutionUserId, FacultyId)
            REFERENCES dbo.Faculties(InstitutionUserId, FacultyId);