之前上课感觉group by 和 一张表变成两张表使用(类似 from user_class as uc1,user_class as uc2)没怎么学好,特此实验一番
user 表(用户即学生)
class表 课程表
user_class表 用户选课表
查询目的 课程成绩低于课程平均分的学生信息。
第一次尝试,实现简单效果
mysql> select uc.* from user_class as uc
where uc.grade < (select avg(grade) from user_class as uc2 where uc2.c_id = uc.c_id);
显示效果:
查询到了需要的数据,找到了比平均分低的学生信息,这个sql只用到了两张虚拟表提供查询学生成绩和平均成绩作为对比。
第二次尝试现在需要把平均成绩显示出来
mysql> select uc.*,
(select avg(grade) from user_class as uc2 where uc2.c_id = uc.c_id) as avg_grade
from user_class as uc
where uc.grade < (select avg(grade) as avg_grade from user_class as uc2 where uc2.c_id = uc.c_id);
显示效果
虽然sql比较冗余,但是效果出来了。 想办法优化
第三次尝试通过之前的方法无法实现优化,现在换种思路
mysql> select uc.*,my.* from user_class as uc,
(select c_id,avg(grade) from user_class as uc group by uc.c_id) as my
where uc.c_id = my.c_id ;
第四次尝试,实现简单显示优化
mysql> select uc.*,my.avg_grade from user_class as uc,
(select c_id,avg(grade) as avg_grade from user_class as uc
group by uc.c_id) as my
where uc.c_id = my.c_id and uc.grade < my.avg_grade ;
最终显示效果优化
mysql> select user.name,uc.*,my.avg_grade,my.num as '选课人数'
from user_class as uc,user ,
(select c_id,avg(grade) as avg_grade,count(grade) as num from user_class as uc group by uc.c_id) as my
where uc.u_id = user.id and uc.c_id = my.c_id
and uc.grade < my.avg_grade ;
主要用到的小功能是 ,一个user_class表在一个sql中可以起两次别名,uc1和uc2 一个用作查询用户信息,一个用作查询平均成绩使用,功能分离,还有就是avg和count函数的使用,相对简单,一开始那个冗余的sql 还是不要用了。