How to create three relational tables in MySQL

WBOY
Release: 2023-05-30 23:10:04
forward
2384 people have browsed it

1.Create student table

create table tbl_stu ( id int not null primary key auto_increment, name varchar(45) not null )engine=innodb default charset=utf8;
Copy after login

How to create three relational tables in MySQL

2.Create subject table

create table tbl_sub ( id int not null primary key auto_increment, subject varchar(45) not null )engine=innodb default charset=utf8;
Copy after login

How to create three relational tables in MySQL

3.Create score table

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) );
Copy after login

How to create three relational tables in MySQL

4. Insert data

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);
Copy after login

5. Query all scores

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;
Copy after login

How to create three relational tables in MySQL

6. Query the average score of students

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;
Copy after login

How to create three relational tables in MySQL

7.Total score ranking

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;
Copy after login

How to create three relational tables in MySQL

The above is the detailed content of How to create three relational tables in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!