MySQL如何创建三张关系表

网友投稿 623 2023-07-04

MySQL如何创建三张关系表

MySQL如何创建三张关系表

1.创建学生表

create table tbl_stu (id int not null primary key auto_increment,name varchar(45) not null)engine=innodb default charset=utf8;登录后复制

2.创建科目表

create table tbl_sub (id int not null primary key auto_increment,subject varchar(45) not null)engine=innodb default charset=utf8;登录后复制

3.创建分数表

create table tbl_scores(id int not null primary key auto_increment,stu_id int,sub_id intscore decimal(5,2),constraint sco_stu foreign key(stu_id) references tbl_stu(id),constraint sco_sub foreign key(sub_id) references tbl_sub(id));登录后复制

4.插入数据

insert into tbl_stu values (0,"小王");insert into tbl_stu values (0,"小宋");insert into tbl_stu values (0,"小李");insert into tbl_sub values (0,"语文");insert into tbl_sub values (0,"数学");insert into tbl_sub values (0,"英语");insert into tbl_scores values (0,1,1,90);insert into tbl_scores values (0,1,2,70);insert into tbl_scores values (0,1,3,82);insert into tbl_scores values (0,2,1,95);insert into tbl_scores values (0,2,2,70);insert into tbl_scores values (0,2,3,84);insert into tbl_scores values (0,3,1,85);insert into tbl_scores values (0,3,2,86);登录后复制

5.查询全部分数

select s3.name,s2.subject,s1.score from tbl_scores as s1inner join tbl_sub as s2 on s1.sub_id = s2.idinner join tbl_stu as s3 on s1.sub_id = s3.id;登录后复制

6.查询学生的平均分

select s3.name,avg(s1.score) from tbl_scores as s1inner join tbl_stu as s3 on s1.sub_id = s3.idgroup by s3.name;登录后复制

7.总分排行榜

select s3.name,sum(s1.score) as s from tbl_scores as s1inner join tbl_stu as s3 on s1.stu_id = s3.idgroup by s3.name order by s desc;登录后复制

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Linux怎么安装mysql5.7
下一篇:mysql中获取时间方式有哪些
相关文章