MySQL 創(chuàng)建三張關(guān)系表實操
更新時間:2022年03月24日 17:15:51 作者:江下下啊
這篇文章主要介紹了MySQL 創(chuàng)建三張關(guān)系表實操,文章說先創(chuàng)建學生表然后科目表和分數(shù)表三張有著密切關(guān)系的表,下文實操分享需要的小伙伴可以參考一下
1.創(chuàng)建學生表
create table tbl_stu ( id int not null primary key auto_increment, name varchar(45) not null )engine=innodb default charset=utf8;
2.創(chuàng)建科目表
create table tbl_sub ( id int not null primary key auto_increment, subject varchar(45) not null )engine=innodb default charset=utf8;
3.創(chuàng)建分數(shù)表
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.插入數(shù)據(jù)
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,"數(shù)學"); 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.查詢?nèi)糠謹?shù)
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;
到此這篇關(guān)于MySQL 創(chuàng)建三張關(guān)系表實操的文章就介紹到這了,更多相關(guān)MySQL 創(chuàng)建關(guān)系表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows環(huán)境下mysql數(shù)據(jù)庫的主從同步備份步驟(單向同步)
本文主要是向大家描述的是在windows環(huán)境之下實現(xiàn)MySQL數(shù)據(jù)庫的主從同步備份的正確操作方案,以下就是文章的詳細內(nèi)容描述2011-05-05Mysql添加用戶和設(shè)置權(quán)限的操作方法
這篇文章主要介紹了Mysql添加用戶和設(shè)置權(quán)限的操作方法,主要包括管理用戶,權(quán)限控制的相關(guān)知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07MySQL中預處理語句prepare、execute與deallocate的使用教程
這篇文章主要介紹了MySQL中預處理語句prepare、execute與deallocate的使用教程,文中通過示例代碼介紹的非常詳細,對大家學習或者使用mysql具有一定的參考學習價值,需要的朋友們下面跟著小編一起來學習學習吧。2017-08-08淺談MySQL 統(tǒng)計行數(shù)的 count
這篇文章主要介紹了MySQL 統(tǒng)計行數(shù)的 count的相關(guān)資料,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07