首页 文章

如何在SQL Server中为表创建复合候选键?

提问于
浏览
1

请考虑以下表格定义......

Table Definition

CREATE TABLE [dbo].[Folders](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [int] NOT NULL,
    [ParentFolderId] [int] NULL
PRIMARY KEY CLUSTERED 
(
    [Id] 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

其他表与此表的主键列 [id] 具有外键关系 .

我希望添加一个自引用外键约束,其中父文件夹id引用同一文件夹表中的另一个记录的Id字段,但UserId也必须匹配...

Self Referencing Foreign Key Constraint

ALTER TABLE [dbo].[Folders]  WITH CHECK ADD  CONSTRAINT [FK_Folders_ParentFolder] FOREIGN KEY([UserId], [ParentFolderId])
REFERENCES [dbo].[Folders] ([UserId], [Id])
GO
ALTER TABLE [dbo].[Folders] CHECK CONSTRAINT [FK_Folders_ParentFolder]
GO

......但我收到错误......

Errors

Msg 1776, Level 16, State 0, Line 64
There are no primary or candidate keys in the referenced table 'dbo.Folders' that match the referencing column list in the foreign key 'FK_Folders_ParentFolder'.
Msg 1750, Level 16, State 0, Line 64
Could not create constraint or index. See previous errors.
Msg 4917, Level 16, State 0, Line 67
Constraint 'FK_Folders_ParentFolder' does not exist.
Msg 4916, Level 16, State 0, Line 67
Could not enable or disable the constraint. See previous errors.

我试图在表中添加一个复合唯一索引来提供候选键但这不起作用,我仍然得到相同的错误 .

Unique Index

CREATE UNIQUE NONCLUSTERED INDEX [IX_Folders_UserParentFolder] ON [dbo].[Folders]
(
    [UserId] ASC,
    [ParentFolderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

如何在 [Id][UserId] 上创建超级/候选键,以便我可以添加自引用外键?请记住,将主键从单个整数转换为复合键将破坏引用Folders表的其他表上的外键 . 这些外键不需要知道UserId .

EDIT:

根据Dan Guzman的建议/评论添加数据库约束就可以了 . 这是约束的定义......

Constraint Definition

ALTER TABLE [dbo].[Folders]
ADD CONSTRAINT AK_Folders_UserId UNIQUE ([UserId], [Id])
GO

1 回答

  • 4

    外键列引用的列必须是主键,唯一约束或唯一索引 . 我建议这里有一个独特的约束:

    ALTER TABLE dbo.Folders
    ADD CONSTRAINT UQ_Folders_UserId_Id UNIQUE(UserId, Id);
    

相关问题