如何在多对多关系表中插入一条记录?

发布于 2024-12-22 07:19:33 字数 498 浏览 6 评论 0原文

例如,我有两个表

A

create table teachers(
id number(4) primary key,
name varchar(20)
);

B

create table students(
id number(4) primary key,
name varchar(20)
);

和第三个表

AB

create table Teacher_Student(
T_Id number(4),
S_Id number(4)
);

以及它们的关系

alter table teacher_student
add constraint s_t_pk Primary key(T_Id, S_Id);

该关系是否正确创建?如果我想添加新学生或老师,插入查询是什么?

For exmple i have two tables

A

create table teachers(
id number(4) primary key,
name varchar(20)
);

B

create table students(
id number(4) primary key,
name varchar(20)
);

and a third table

AB

create table Teacher_Student(
T_Id number(4),
S_Id number(4)
);

and their relationship

alter table teacher_student
add constraint s_t_pk Primary key(T_Id, S_Id);

Is this relationship is created correctly? and what would be the insertion query if i want to add a new student or a teacher.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

成熟稳重的好男人 2024-12-29 07:19:33

建议:还添加引用完整性约束:

alter table teacher_student
   add constraint s_t_fk_t foreign key (T_Id)
   references teachers (id)
   on delete cascade
   on update cascade;

alter table teacher_student
   add constraint s_t_fk_s foreign key (S_Id)
   references students (id)
   on delete cascade
   on update cascade;

Suggestion: also add referential integrity constraints:

alter table teacher_student
   add constraint s_t_fk_t foreign key (T_Id)
   references teachers (id)
   on delete cascade
   on update cascade;

alter table teacher_student
   add constraint s_t_fk_s foreign key (S_Id)
   references students (id)
   on delete cascade
   on update cascade;
三五鸿雁 2024-12-29 07:19:33

通常的操作需要学生表和教师表的主键,然后需要来自 Teacher_Student 的教师和学生的 T_Id 和 S_id 的外键。

完成此操作后,插入到学生和教师,只会检查其键的唯一性,即,不能有两个 id 为 1 的学生。

插入到 Teacher_Student 将检查关系的唯一性,并且插入的id 存在于各自的表中。

PS 缩写数据库对象名称是一个非常令人反感的习惯。

Usual manouever for this would require primary keys for student and teacher tables, and then foreign keys for T_Id and S_id to Teachers and Students from Teacher_Student.

When you've done that, inserting to student and teacher, would only check uniqueness of their keys, i.e , you can't have two student's with an id of 1.

Inserting to Teacher_Student would check uniqueness of the relationship, and that the inserted ids exist in their respective tables.

PS abbreviating database object names is a very objectionable habit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文