首頁 > 資料庫 > mysql教程 > MySQL如何建立三張關係表

MySQL如何建立三張關係表

WBOY
發布: 2023-05-30 23:10:04
轉載
2470 人瀏覽過

1.建立學生表格

create table tbl_stu (

id int not null primary key auto_increment,

name varchar(45) not null

)engine=innodb default charset=utf8;
登入後複製

MySQL如何建立三張關係表

2.建立科目表

create table tbl_sub (

id int not null primary key auto_increment,

subject varchar(45) not null

)engine=innodb default charset=utf8;
登入後複製

MySQL如何建立三張關係表

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)
);
登入後複製

MySQL如何建立三張關係表

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;
登入後複製

MySQL如何建立三張關係表

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;
登入後複製

MySQL如何建立三張關係表

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如何建立三張關係表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板