MySQL 创建三张关系表实操

吾爱主题 阅读:140 2024-04-01 23:23:52 评论:0

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 int

score 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 s1

inner join tbl_sub as s2 on s1.sub_id = s2.id

inner join tbl_stu as s3 on s1.sub_id = s3.id;

 

6.查询学生的平均分

select s3.name,avg(s1.score) from tbl_scores as s1

inner join tbl_stu as s3 on s1.sub_id = s3.id

group by s3.name;

 

7.总分排行榜

select s3.name,sum(s1.score) as s from tbl_scores as s1

inner join tbl_stu as s3 on s1.stu_id = s3.id

group by s3.name order by s desc;

到此这篇关于MySQL 创建三张关系表实操的文章就介绍到这了,更多相关MySQL 创建关系表内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.51cto.com/u_15173612/5098740

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容