我有4个SQL表:用户、学生、教授和出版物。
所以我有:
create table dbo.[User] (
Id int identity not null
constraint PK_User_Id primary key clustered (Id),
-- Other user columns
)
create table dbo.Student (
UserId int not null
constraint PK_Student_UserId primary key clustered (Id),
-- Other student columns
)
create table dbo.Professor (
UserId int not null
constraint PK_Professor_Id primary key clustered (Id),
-- Other student columns
)
create table dbo.Publication (
Id int identity not null
constraint PK_Publication_Id primary key clustered (Id),
UserId int not null
-- Other student columns
)
alter table dbo.Student
add constraint FK_Student_UserId foreign key (UserId) references dbo.[User](Id);
alter table dbo.Professor
add constraint FK_Professor_UserId foreign key (UserId) references dbo.[User](Id);
alter table dbo.Publication
add constraint FK_Publication_UserId foreign key (UserId) references dbo.Professor(Id);问题
我是否应该在教授表和学生表中有一个作为PK的列Id?
例如,将(Id,UserId)作为教授的PK (学生相同)
那么发布将引用Professor.Id而不是Professor.UserId。
我之所以问这个问题,是因为让出版物引用教授表中的UserId听起来很奇怪,当我有更多的表时,这可能会让人感到困惑。
有人能在这个问题上给我提个建议吗?
发布于 2015-04-13 21:41:31
在当前的模式安排中,在不知道用例(以编程方式)的情况下,可以提出这样的论点,即您不需要任何扩展表的Id标识列。我假设这将是与User表的1到1的关系,所以您至少希望对UserID列有一个唯一的约束,这可以通过将它作为PK来获得。
发布于 2015-04-14 19:09:50
我想考虑的是:
如果是这样的话,为什么不给每个教授一个唯一的Id (ProfessorId),并且只为User表创建一个外键(UserId,您可以调用这个UserFk)。
在发布表中,您可以通过教授的id引用他/她,并将其称为ProfessorFk。这样您就可以在表之间创建非常有效的引用。发布表还将单个PublicationId作为主键。
如果我错了,我不知道你的用例。但是,一个教授可以有多个出版物,但一个出版物也可以由多个教授撰写,这似乎是合理的吗?这意味着你需要一个额外的表格之间的出版和教授之间的n-n关系。
关于创建一个组合键的教授密钥(Id,UserId)。我个人不喜欢组合键,如果您想从您的出版物表中引用这位教授,您需要两列。这也意味着您可以为同一用户设置多个教授,如果是,请选择单一Id选项。
这意味着我将创建以下设置:
所以,这部分是基于你想要用你的数据做什么,也部分是你的偏好。
https://stackoverflow.com/questions/29615375
复制相似问题