【Mysql经典例题讲解(四)】
本文接上篇文章,继续讲解Mysql例题;
26.查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列:
select sc.cid,AVG(score)
from sc
GROUP BY cid
ORDER BY AVG(score) desc,cid asc
27.查询平均成绩大于等于80的所有学生的学号、姓名和平均成绩
select student.sid,student.sname,t1.avgscore
from student INNER JOIN
(select sc.sid,AVG(sc.score) as avgscore from sc
GROUP BY sc.sid
HAVING AVG(sc.score) >= 80) as t1
on student.SId = t1.SId
28.查询课程名称为「数学」,且分数低于60的学生姓名和分数
select student.sname,t1.score
from student INNER JOIN
(select sc.sid,sc.score
from sc,course
where sc.cid = course.cid
and course.cname = '数学'
and sc.score < 60) as t1
on student.sid = t1.sid
29.查询所有学生的课程及分数情况(存在学生没成绩,没选课的情况)
select student.sid,sc.cid,sc.score
from Student left join sc
on student.sid = sc.sid
30. 查询任何一门课程成绩在 70 分以上的姓名、课程名称和分数
select student.sname,course.cname,sc.score
from student,sc,course
where sc.score >= 70
and student.sid = sc.sid
and sc.cid = course.cid
31.查询存在不及格的课程
select DISTINCT sc.cid
from sc
where sc.score < 60
32.查询课程编号为 01 且课程成绩在 80 分以上的学生的学号和姓名
select sc.sid,student.sname
from sc,student
where sc.cid = "01"
and sc.score > 80
and sc.sid = student.sid
33. 求每门课程的学生人数
select sc.cid,count(*) as 学生人数
from sc
GROUP BY sc.cid
34.成绩不重复,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩
select student.*,sc.score
from student,course,teacher,sc
where course.cid = sc.cid
and course.tid = teacher.tid
and teacher.tname = '张三'
and student.sid = sc.sid
ORDER BY score desc
LIMIT 1
35.成绩有重复的情况下,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩
select student.*,sc.score from student,teacher,course,sc
where teacher.tid = course.tid
and sc.sid = student.sid
and sc.cid = course.cid
and teacher.tname = "张三"
and sc.score = (
select Max(sc.score)
from sc,student,teacher,course
where teacher.tid = course.tid
and sc.sid = student.sid
and sc.cid = course.cid
and teacher.tname = "张三"
);