学生表和课程表可以多对多
一个学生可以学多门课程
一门课程可以有多个学生: 多对多
一个学生对应一个班级
一个班级对应多个学生: 一对多
一个老师对应多个学生
多个学生对应一个老师:一对多
一个老师教一门课
一门课对应一个老师: 一对一
一对多(foreign key):
学生表要关联班级表,多个学生属于一个班级. 班级是被关联的表
创建班级表
create table class(
-> id int primary key auto_increment,
-> caption char(20)
-> );
插入一条数据
insert into class(caption) values(‘三年二班’),(‘一年三班’),(‘三年一班’);
创建学生表
create table student (
-> id int primary key auto_increment,
-> name varchar(20),
-> sex enum(‘male’,‘female’) default ‘male’,
-> class_id int,
-> foreign key(class_id) references class(id)
-> );
1:n也就是一对多的形式,把外键放在学生里面
插入学生数据和外键值
insert into student(name,class_id) values(‘钢炮’,1),(‘狗蛋’,2),(‘猪猪’,3);
创建教师表
对这个班级来说,一门课程只有一个老师,一个老师只会教一门课程. 所以是一对一的关系
create table teacher(
->id int primary key auto_increment,
->name varchar(20));
插入一条数据
insert into teacher(name) value(‘ff’),(‘ff1’),(‘ff2’);
创建课程表
create table course (
-> id int primary key auto_increment,
-> name varchar(20),
-> teacher_id int unique,
-> foreign key(teacher_id) references teacher(id)
-> );
insert into course(name,teacher_id) values (‘数学’,1),(‘语文’,2);
一个学生可以学多门课程,一门课程可有有多个学生, 他们就是多对多的关系.
create table student2course (
-> id int primary key auto_increment,
-> student_id int,
-> course_id int,
-> foreign key(student_id) references student(id),
-> foreign key(course_id) references course(id),
-> score int
-> );
insert into student2course (student_id,course_id,score) values(1,1,60),(1,2,59),(2,2,100);
多表联合查询学生姓名,班级,课程,老师,分数
select S.name,C.caption,course.name,T.name,student2course.score
-> from student S,teacher T,class C,course,student2course
-> where S.class_id=C.id and S.id=student2course.student_id and course.id=student2course.course_id and T.id=course.teacher_id;
————————————————
版权声明:本文为优快云博主「love_521_」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/love_521_/article/details/84798264