#【例6.16】查询各门课程的最高分、最低分、平均成绩。
use stusys;
select cno as 课程号,max(grade) as 最高分,min(grade) as 最低分,avg(grade) as 平均成绩
from score
where grade is not null and cno='8001'
group by cno;
#【例6.17】查询平均成绩在90分以上的学生的学号和平均成绩。
select sno as 学号,avg(grade) as 平均成绩 from score
group by sno
having avg(grade)>80
order by avg(grade) desc
limit 0 ,3;
#【例6.18】查询至少有5名学生选修且以8开头的课程号和平均分数。
select cno as 课程号,avg(grade) as 平均分数 from score
where cno like '8%'
group by cno
having count(*)>5;
#【例6.19】将计算机专业的学生按出生时间降序排序。
select * from student
where speciality='计算机'
order by sbirthday desc;
#【例6.20】查询成绩表中成绩前3位学生的学号、课程号和成绩。
select sno, cno, grade from score
order by grade desc
limit 0, 3;
#【例6.21】采用交叉连接查询教师和和讲课地点所有可能组合。
select * from teacher,lecture;
select a.tno,a.tname,b.cno,b.location
from teacher a,lecture b
where a.tno=b.tno;
select a.tno,a.tname,b.cno,b.location
from teacher a inner join lecture b on a.tno=b.tno;
select tname, location
from teacher, lecture;
#【例6.22】查询每个学生选修课程的情况。
select student. *, score. * from student,score
where student.sno=score.sno;
#【例6.23】查询选修了数据库系统课程且成绩在80分以上的学生情况。
select a.sno, sname, cname, grade from student a,score b, course c
where a.sno=b.sno and b.cno=c.cno and cname='数据库系统' and grade>=80;
select b.cno as 学号,b.sname as 姓名,a.grade as 数据库成绩
from score a,student b, course c
where c.cname='数据库系统' and a.grade>80 and c.cno=a.cno and a.sno=b.sno;
select b.cno as 学号,b.sname as 姓名,a.grade as 数据库成绩
from score a join student b on a.sno=b.sno join course c on a.cno=c.cno where c.cname='数据库系统' and a.grade>80;
#【例6.24】对例6.22进行自然连接查询。
select * from student natural join score;
#【例6.25】查询选修了“1201”课程的成绩高于学号为“191002”的成绩的学生姓名。
use stusys;
select a.cno, a.sno, a.grade from score a, score b
where a.grade>b.grade and a.cno='1201' and b.cno='1201' and b.sno='191002'
order by a.grade desc;
#【例6.26】采用左外连接查询教师任课情况。
select tname, cno from teacher left join lecture on (teacher.tno=lecture.tno);
#【例6.27】采用右外连接查询教师任课情况。
select tno, cname from lecture join course on (course.cno=lecture.cno);
#【例6.28】查询选修了课程号为8001的课程的学生情况。
select * from student
where sno in (select sno from score where cno='8001');
#【例6.29】查询选修某课程的学生人数多于4人的教师姓名。
select tname as 教师姓名 from teacher
where tno in(select tno from lecture where cno in (select a.cno from course a,score b where a.cno=b.cno group by a.cno having count(a.cno)>4))
#【例6.30】查询比所有通信专业学生年龄都小的学生。
select * from student
where sbirthday>all (select sbirthday from student where speciality='通信');
#【例6.31】查询选修1004课程的学生姓名。
select sname as 姓名 from student
where exists (select * from score where score.sno=student.sno and cno='1004');