gpt4 book ai didi

sql - 如何建立外键关系

转载 作者:搜寻专家 更新时间:2023-10-30 23:03:21 28 4
gpt4 key购买 nike

我有三张 table 。

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 中的复合键。但是无法维护外键,因为单个表中没有两列。

如何解决这个问题。

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

主要需求是

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

编辑:如果您不需要此表中的代理键,并且不太关心它可能的子项,则可以通过从代理主键切换到自然键来简化结构一。随着表变得越来越窄,它将通过减少磁盘占用空间来提高高负载场景下的性能:

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

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

关于sql - 如何建立外键关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29643107/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com