具有到同一表的外键关系的复合主键

时间:2014-01-24 10:21:58

标签: sql-server foreign-keys primary-key composite-key

所以我有一个名为“Event”的表,我想创建另一个表,其中一个事件可以包含来自同一个表的更多事件。这是我到目前为止所做的。

这是现有的表格......

CREATE TABLE [dbo].[EventEvents]
    (
       [step_id] [uniqueidentifier] NOT NULL PRIMARY KEY,
       [title] [nvarchar](200) NOT NULL,
       [Enabled] [bit] NOT NULL,
    )

然后这是我要创建的表格......

CREATE TABLE [dbo].[EventEvents]
(
   [EventId] [uniqueidentifier] NOT NULL,
   [EventChildId] [uniqueidentifier] NOT NULL,
   [Enabled] [bit] NOT NULL,
   CONSTRAINT [PK_EventEvents] PRIMARY KEY ([EventId], [EventChildId]),
   CONSTRAINT [FK_Event_EventChild] FOREIGN KEY ([EventId],[EventChildId]) REFERENCES [dbo].[Event] ([step_id], [step_id])
)

因此,EventId和EventChildId都是Event的外键 - step_id,因为1事件可以将其他事件作为其中的子项。但我需要EventId和EventChildId都是复合主键。 我怎么能这样做?

目前我收到错误消息:

  

在FOREIGN KEY约束键列表中指定的重复列

由于

1 个答案:

答案 0 :(得分:0)

我已经明白了,谢谢。

    CREATE TABLE [dbo].[EventChildren]
(
[EventId] [uniqueidentifier] NOT NULL,
[EventChildId] [uniqueidentifier] NOT NULL,
[Enabled] [bit] NOT NULL,
CONSTRAINT [EventEvents] PRIMARY KEY CLUSTERED 
(
    [EventId] ASC,
    [EventChildId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[EventChildren]  WITH CHECK ADD  CONSTRAINT [FK_EventChildren_Event] FOREIGN KEY([EventId])
REFERENCES [dbo].[Event] ([step_id])
GO

ALTER TABLE [dbo].[EventChildren]  WITH CHECK ADD  CONSTRAINT [FK_EventChildren_EventChild] FOREIGN KEY([EventChildId])
REFERENCES [dbo].[Event] ([step_id])
GO

ALTER TABLE [dbo].[EventChildren] CHECK CONSTRAINT [FK_EventChildren_Event]
GO
ALTER TABLE [dbo].[EventChildren] CHECK CONSTRAINT [FK_EventChildren_EventChild]
GO