2014-01-29 41 views
2

我在SQL服務器的兩個表:錯誤,同時增加外鍵,組合鍵

第一臺Message_Child有一個複合主鍵(的MessageId,childID的)

Message_Child (MessageId, ChildId, Date) 

二表應包含一個外鍵到Message_Child表,所以我創建了兩列:MessageId和ChildId。

Request (RequestId, MessageId, ChildId, type) 

我創建的約束如下:

Alter table Request 
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES Message_Child(MessageId, ChildId); 

但我發現了以下錯誤:

有在引用表上沒有主或候選鍵「Message_Child」它們與外鍵「FK_ 請求 _534D60F1」中的引用列表匹配。

編輯 添加代碼:

Message_Child表:

CREATE TABLE [dbo].[Message_Child](
[ChildId] [int] NOT NULL, 
[MessageId] [int] NOT NULL, 
[Date] [datetime] NULL, 
CONSTRAINT [PK_Message_Child] PRIMARY KEY CLUSTERED 
(
[ChildId] ASC, 
[MessageId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

ALTER TABLE [dbo].[Message_Child] WITH CHECK ADD CONSTRAINT   [FK_Message_Child_Child_ChildId] FOREIGN KEY([ChildId]) 
REFERENCES [dbo].[Child] ([ChildId]) 
GO 

ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Child_ChildId] 
GO 

ALTER TABLE [dbo].[Message_Child] WITH CHECK ADD CONSTRAINT  [FK_Message_Child_Message_MessageId] FOREIGN KEY([MessageId]) 
REFERENCES [dbo].[Message] ([MessageId]) 
GO 

ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Message_MessageId] 
GO 

請求隊列表:

CREATE TABLE [dbo].[RequestQueue](
[RequestQueueId] [int] IDENTITY(1,1) NOT NULL, 
[PIN] [nvarchar](max) NULL, 
[MessageId] [int] NULL, 
[ChildId] [int] NULL, 
CONSTRAINT [PK_RequestQueue] PRIMARY KEY CLUSTERED 
(
[RequestQueueId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

ALTER TABLE [dbo].[RequestQueue] WITH CHECK ADD CONSTRAINT [FK_RequestQueue_MessageChildId] FOREIGN KEY([RequestQueueId]) 
REFERENCES [dbo].[RequestQueue] ([RequestQueueId]) 
GO 

ALTER TABLE [dbo].[RequestQueue] CHECK CONSTRAINT [FK_RequestQueue_MessageChildId] 
GO 

然後,我添加了這個:

Alter table [DayCareDB].[dbo].[RequestQueue] 
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES [DayCareDB].[dbo].[Message_Child](MessageId, ChildId); 
+0

這個錯誤很自我解釋。您不能擁有引用3列組合主鍵的2列外鍵。 – Kermit

+0

否複合鍵由兩列組成。見第二行。日期不在複合鍵中。 – Hanady

+0

哎呀,錯誤地讀你的表結構作爲你的鑰匙。 – Kermit

回答

5

這裏的關鍵順序很重要。您需要使用(ChildID, MessageID)其中訂單,因爲這是您的主鍵定義中的關鍵順序。

Alter table [DayCareDB].[dbo].[RequestQueue] 
ADD FOREIGN KEY (ChildId, MessageId) 
REFERENCES [DayCareDB].[dbo].[Message_Child](ChildId, MessageId);