登录
首页 >  数据库 >  MySQL

MySQL创建三张关系表实操

来源:脚本之家

时间:2022-12-29 12:14:23 221浏览 收藏

本篇文章给大家分享《MySQL创建三张关系表实操》,覆盖了数据库的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

1.创建学生表

create table tbl_stu (

id int not null primary key auto_increment,

name varchar(45) not null

)engine=innodb default charset=utf8;

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据

2.创建科目表

create table tbl_sub (

id int not null primary key auto_increment,

subject varchar(45) not null

)engine=innodb default charset=utf8;

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据_02

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)
);

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据_03

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;

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据_04

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;

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据_05

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;

#yyds干货盘点# 17 MySQL 创建三张关系表_插入数据_06

文中关于mysql的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《MySQL创建三张关系表实操》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表