简体   繁体   中英

How to establish foreign key relationship

I got three 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.

This is the requirement.

Steps i tried :

I made ProjectId, UserId as composite key in workFlow. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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