mysql四表連查

滿心歡喜...發表於2020-12-17

mysql四表連查在這裡插入圖片描述

建立學生表:
create table student(
sid int auto_increment primary key not null,
sname varchar(20),
sxday date,
sex varchar(20)
)
檢視:
desc student;
在表裡新增資料:
insert into student values(1,“ss”,“1990-01-01”,“男”),(2,“小虎”,“1990-05-20”,“男”),(3,“小花”,“1991-03-11”,“女”),(4,“趙磊”,“1999-12-25”,“男”)
檢視新增後的表:
select * from student;

建立老師表:
create table teacher(
tid int auto_increment primary key not null,
tname varchar(20)
)
檢視:
desc teacher;
在表裡新增資料:
insert into teacher values(1,“韓老師”),(2,“王老師”),(3,“劉老師”),(4,“李老師”),(5,“胡老師”),(6,“馬老師”)
檢視新增後的表:
select * from teacher;

建立課程表:
create table course(
cid int auto_increment primary key not null,
cname varchar(20),
tid int,
foreign key(tid) references teacher(tid)
)
檢視:
desc course;
在表裡新增資料:
insert into course values(1,“語文”,1),(2,“數學”,3),(3,“英語”,5),(4,“物理”,2),(5,“化學”,4),(6,“政治”,6)
檢視新增後的表:
select * from course;
– 小虎同學的數學成績
select sc.scores from scores sc
LEFT JOIN students s ON sc.sid=s.sid
LEFT JOIN courses c On sc.cid=c.cid
where s.sid=2 and c.cid=2

– 馬老師都教了哪些課程
select t.tname,c.cname from teachers t INNER JOIN courses c on t.tid=c.tid where t.tname=‘馬老師’

– 第三題
select m.name,m.scores from(select s.name,a.scores from scores a
LEFT JOIN students s ON a.sid=s.sid
LEFT JOIN courses c ON a.cid=c.cid
where c.cid=2 order by a.scores desc limit 1)as m

相關文章