简体   繁体   English

如何建立外键关系

[英]How to establish foreign key relationship

I got three tables. 我有三张桌子。

User
Project
WorkFlow

In workflow ProjectId, UserId together should never repeat. 在工作流ProjectId中,UserId一起不应重复。 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应该出现在Project表中,而UserId应该出现在User表中。

This is the requirement. 这是必需的。

Steps i tried : 我尝试过的步骤:

I made ProjectId, UserId as composite key in workFlow. 我在WorkFlow中将ProjectId, UserId为组合键。 But cant be able to maintain foreign key since two columns are not available in single table. 但由于单个表中没有两列,因此无法维护外键。

How to resolve this. 如何解决这个问题。

I am open to change my design also, since this is the initial stage of my development. 我也愿意改变设计,因为这是我开发的初始阶段。

Main reuirement is 主要招募是

One table to store project (project table) related informations and the other one(workFlow) hold the record which project is assigned to which user. 一个表用于存储项目(项目表)的相关信息,另一个表(工作流)保存将哪个项目分配给哪个用户的记录。

Foreign keys do not control uniqueness; 外键不能控制唯一性。 they only control referential integrity. 它们仅控制参照完整性。 For uniqueness, you need unique constraints: 为了唯一,您需要唯一的约束:

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)
);

EDIT: If you don't need a surrogate key in this table, and don't care much about its possible children, you can simplify the structure by switching from surrogate primary key to the natural one. 编辑:如果您在此表中不需要代理键,并且不关心其可能的子代,则可以通过从代理主键切换为自然键来简化结构。 With table becoming more narrow, it will increase performance in high load scenarios by reducing its disk footprint: 随着表变得越来越狭窄,它将通过减少磁盘占用空间来提高高负载情况下的性能:

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),
);

And yes, constraints should be uniquely named, it will make schema comparisons and updates much easier. 是的,约束应该唯一地命名,这将使架构比较和更新变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM