引用表中没有主键或候选键...与外键中的引用列列表匹配

时间:2018-07-18 22:15:48

标签: sql foreign-keys composite-key

创建表[dbo].[WeibullSummaryDetails]时遇到此错误。

这是我的两个桌子

CREATE TABLE [dbo].[WeibullFilterDetails]
(
        [WeibullFilterDetailsId] [int] IDENTITY(1,1) NOT NULL,
        [ProjectTeamId] int not null,
        [WeekStartDate] date not NULL,
        [WeekEndDate] date  not null ,
        [IsRefreshed] bit NULL,

        CONSTRAINT FK_WeibullFilterDetails_WeibullFilterDetails 
            FOREIGN KEY ([ProjectTeamId])
            REFERENCES [dbo].[ProjectTeams]([Id]),
        PRIMARY KEY ([ProjectTeamId], [WeibullFilterDetailsId])
) 

CREATE TABLE [dbo].[WeibullSummaryDetails]
(
    [WeibullSummaryDetailsId] [int] IDENTITY(1,1) NOT NULL,
    [WeibullFilterDetailsId] int not null,
    [ProjectTeamId] int not null,
    [ActualEstimatedBugCount] int NULL,
    [CurrentBugCount] int NULL,
    [PercentageBugFound] float NULL,
    [PercentageBugResolved] float NULL,
    [BugsToFind] int NULL,
    BugsToResolve int NULL,
    LinearEquation nvarchar(100) null,
    RSquare float NULL,
    Shape float NULL,
    Scale float NULL

    PRIMARY KEY ([WeibullSummaryDetailsId], [WeibullFilterDetailsId],[ProjectTeamId]),
    CONSTRAINT FK_WeibullSummaryDetails_WeibullFilterDetails 
        FOREIGN KEY ([WeibullFilterDetailsId],[ProjectTeamId])
        REFERENCES [dbo].[WeibullFilterDetails]([WeibullFilterDetailsId],[ProjectTeamId])
) 

详细的错误消息

  

信息1776,级别16,状态0,第14行
  在引用表'dbo.WeibullFilterDetails'中没有与外键'FK_WeibullSummaryDetails_WeibullFilterDetails'中的引用列列表匹配的主键或候选键。

     

信息1750,级别16,状态0,第14行
  无法创建约束。查看以前的错误。

我还看到了有关此错误的其他文章,通常提供的解决方案是,如果父表具有复合键,则两个列也应同时存在于子表中,并应用于外键约束。

这正是我在这里所做的,但仍然出现此错误。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

对于[dbo].[WeibullFilterDetails],您将主键定义为([ProjectTeamId],[WeibullFilterDetailsId]),但是在REFERENCES子句中,您写了([WeibullFilterDetailsId],[ProjectTeamId]) -顺序不匹配。试试:

CREATE TABLE [dbo].[WeibullSummaryDetails](
    ...
    FOREIGN KEY ([ProjectTeamId],[WeibullFilterDetailsId])
    REFERENCES [dbo].[WeibullFilterDetails]([ProjectTeamId],[WeibullFilterDetailsId])
);