如何在多对多关系表中插入一条记录?
例如,我有两个表
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议:还添加引用完整性约束:
Suggestion: also add referential integrity constraints:
通常的操作需要学生表和教师表的主键,然后需要来自 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.