假设现在有三张表:
student 表含有 student_id(主键), name, age, sex.。
score表 student_id(主键), course_id, score。
course 表 course_id(主键), name。
在同一个Sql语句中,where> group by > having 出现,如果省略了group by ,使用having相当于where的功能
1、查询所有学生的学号,选课数,总成绩
select student_id,count(course_id),sum(score) from score group by student_id
2、查询所有学生的学号,姓名,选课数,总成绩(需要两张表,以student_id作为共同索引)
select s.student_id, stu.name, count(s.course_id), sum(s.score)
from score s,
student stu where s.student_id = stu.student_id group by s.student_id
3、查询平均成绩大于60分的同学的学号和平均成绩
select student_id , avg(score) from score where avg(score) > 60 group by student_id
select student_id , avg(score) from score group by student_id having avg(score) > 60
4、取出student_id为1的学生成绩情况
select * from score where student_id = 1 等同于
select * from score having student_id =1
5、查询没有学全所有课的同学学号和姓名
要求返回学号与姓名,所以要查询student表,但是要求学全,还得看score表
select s.student_id, stu.name from student stu, score s where s.student_id = stu.student_id group by s.student_id having count(*) <(select count(*) from course)