一.建表和加载数据
1.student表
create table if not exists student(s_id int,s_name string,s_birth string,s_sex string)
row format delimited
fields terminated by ','
;
load data local inpath '/root/data.txt' into table student;
2.course表
create table if not exists course(c_id int,c_course string,t_id int)
row format delimited
fields terminated by ','
;
load data local inpath '/root/data.txt' into table course;
3.teacher表
create table if not exists teacher(t_id int,t_name string)
row format delimited
fields terminated by ','
;
load data local inpath '/root/data.txt' into table teacher;
4.score表
create table if not exists score(s_id int,c_id int, s_score DOUBLE)
row format delimited
fields terminated by ','
;
load data local inpath '/root/data.txt' into table score;
二.查询"01"课程比"02"课程成绩高的学生的信息及课程分数?
答案①:
select stu.*,c.*
from student stu
join score a on a.c_id = '01' and a.s_id= stu.s_id
left join score b on b.c_id = '02' and b.s_id= stu.s_id
join score c on c.s_id= stu.s_id
where a.s_score > b.s_score or b.s_score is null
;
答案②:
select stu.*,c.*
from student stu
left join score a on a.c_id = '02' and a.s_id= stu.s_id
join score b on b.c_id = '01' and b.s_id= stu.s_id
join score c on c.s_id= stu.s_id
where a.s_score < b.s_score or a.s_score is null
;
三.查询"01"课程比"02"课程成绩低的学生的信息及课程分数:
答案①:
select stu.*,c.*
from student stu
join score a on a.c_id = '02' and a.s_id= stu.s_id
left join score b on b.c_id = '01' and b.s_id= stu.s_id
join score c on c.s_id= stu.s_id
where a.s_score > b.s_score or b.s_score is null
;
答案②:
select stu.*,c.*
from student stu
left join score a on a.c_id = '01' and a.s_id= stu.s_id
join score b on b.c_id = '02' and b.s_id= stu.s_id
join score c on c.s_id= stu.s_id
where a.s_score < b.s_score or a.s_score is null
;
总结:对于二题和三题的查询连接的方法:谁大就把谁放在左边,谁小就把谁舍弃。
四.查询平均成绩大于等于60分的同学的学生编号和学生姓名和平均成绩?
答案①:
select
a.s_id,stu.s_name,avg(a.s_score) as avgscore
from score a
join student stu on a.s_id = stu.s_id
group by a.s_id,stu.s_name
having avgscore >= 60
;
答案②:
select
a.s_id,stu.s_name,avg(a.s_score)>=60
from score a
join student stu on a.s_id = stu.s_id
group by a.s_id,stu.s_name
;
五.查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩?
答案①:
select
a.s_id,stu.s_name,avg(a.s_score) as avgscore
from score a
join student stu on a.s_id = stu.s_id
group by a.s_id,stu.s_name
having avgscore < 60
union all
select stu.s_id,stu.s_name,NULL as avgscore
from student stu
left join score a on stu.s_id = a.s_id
where a.s_score is null
;
六.查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
答案:
select stu.s_id,stu.s_name,count(sc.s_id) as totalSubjects,sum(sc.s_score) as sumScores
from student stu left join score sc on stu.s_id=sc.s_id
group by stu.s_id,stu.s_name;
七.查询"李"姓老师的数量?
select count(1)from teacher where t_name like