如何建立外键关系

How to establish foreign key relationship

我得到了三个 tables。

User
Project
WorkFlow

In workflow ProjectId, UserId together should never repeat. Thats my requirement.I mean the combination should never repeat.

And the ProjectId should be present in the Project table and UserId should be present in the User table.

这是要求。

我尝试的步骤:

我将 ProjectId, UserId 作为 workFlow 中的组合键。但是无法维护外键,因为两个列在单个 table.

中不可用

如何解决这个问题。

我也愿意改变我的设计,因为这是我开发的初始阶段。

主要需求是

One table to store project (project table) related informations and the other one(workFlow) hold the record which project is assigned to which user.

外键不控制唯一性;他们只控制参照完整性。对于唯一性,您需要唯一约束:

create table dbo.Workflow (
    Id int identity(1,1) primary key,
    ProjectId int not null,
    UserId int not null,
    foreign key (ProjectId) references dbo.Project (Id),
    foreign key (UserId) references dbo.[User] (Id),
    unique (UserId, ProjectId)
);

编辑: 如果你不需要这个 table 中的代理键,并且不太关心它的可能 children,你可以通过从代理主键切换到自然主键来简化结构。随着 table 变得越来越窄,它将通过减少磁盘占用空间来提高高负载情况下的性能:

create table dbo.Workflow (
    ProjectId int not null,
    UserId int not null,
    primary key (UserId, ProjectId)
    foreign key (ProjectId) references dbo.Project (Id),
    foreign key (UserId) references dbo.[User] (Id),
);

是的,约束应该唯一命名,这将使模式比较和更新更容易。