在具有一对多关系的两个表之间进行映射的最佳方法是什么?

时间:2022-08-01 20:12:19

Is it best to create third table with primary key of each table as foreign key ? or add foreign key to first table? For example student table and project table each project has many students.

是否最好创建第三个表,每个表的主键作为外键?或者将外键添加到第一个表?例如,学生表和项目表每个项目都有很多学生。

2 个解决方案

#1


3  

If you indeed have a 1-many relationship, then you add a foreign key to the first table. For instance:

如果您确实具有1-many关系,则将外键添加到第一个表。例如:

create table students (
     . . . 
    projectId int not null references project(projectId)
);

The not null makes this 1-many. In most cases, you probably want 0/1-many. If so, then remove the not null constraint.

not null使这个1-many。在大多数情况下,您可能需要0/1-many。如果是,则删除非空约束。

You would only introduce a third table (known as an "association table", "junction table", "cross table" and other names) if students could work on more than one project.

如果学生可以处理多个项目,您只会引入第三个表(称为“关联表”,“联结表”,“交叉表”和其他名称)。

Note that you might want a third table if the student-project relationship can change over time. At any given time, a student works on one project, but over time, if the student can work on more than one.

请注意,如果学生 - 项目关系可能随时间发生变化,您可能需要第三个表。在任何时候,学生都在一个项目上工作,但是如果学生可以在一个以上的项目上工作,那么随着时间的推移。

#2


1  

If it is one to many just add new column as foreign key (projectId) in student table

如果是一对多,只需在学生表中添加新列作为外键(projectId)

#1


3  

If you indeed have a 1-many relationship, then you add a foreign key to the first table. For instance:

如果您确实具有1-many关系,则将外键添加到第一个表。例如:

create table students (
     . . . 
    projectId int not null references project(projectId)
);

The not null makes this 1-many. In most cases, you probably want 0/1-many. If so, then remove the not null constraint.

not null使这个1-many。在大多数情况下,您可能需要0/1-many。如果是,则删除非空约束。

You would only introduce a third table (known as an "association table", "junction table", "cross table" and other names) if students could work on more than one project.

如果学生可以处理多个项目,您只会引入第三个表(称为“关联表”,“联结表”,“交叉表”和其他名称)。

Note that you might want a third table if the student-project relationship can change over time. At any given time, a student works on one project, but over time, if the student can work on more than one.

请注意,如果学生 - 项目关系可能随时间发生变化,您可能需要第三个表。在任何时候,学生都在一个项目上工作,但是如果学生可以在一个以上的项目上工作,那么随着时间的推移。

#2


1  

If it is one to many just add new column as foreign key (projectId) in student table

如果是一对多,只需在学生表中添加新列作为外键(projectId)