数据分析MySQL阶段测验简答题

有四张表

用户表:student  列名:stu_id,stu_name

学生分数表:student_score  列名:stu_id,score

班级表:class  列名:class_id,class_name

班级用户表:class_student  列名:class_id,stu_id

使用SQL语句实现:

1、实现学生的分数>80,并且<90的stu_id,stu_name,score

2、实现获取班级名称为'实验班'的班级的平均分

3、获取班级人数>40的班级,输出班级id,班级名称,班级人数

解:

1、

mysql> select student.stu_id,student.stu_name,student_score.score from student
    -> left join student_score
    -> on student.stu_id = student_score.stu_id
    -> where student_score.score between 80 and 90;

解析:

用到二表左连,生成临时表格后输出 stu_id,stu_name,score三列,其中where子句使用between and语法限定条件>80<90的值

2、

mysql> select class.class_name,avg(score)
    ->  from class inner join class_student
    ->  on class.class_id = class_student.class_id
    ->  join student_score
    ->  on class_student.stu_id = student_score.stu_id
    ->  where class.class_name = '实验班';

解析:

用到三表内连,生成临时表格后输出class_name,avg(score)两列,其中where子句限定class_name='实验班'

3、

mysql> select class.class_id,class.class_name,count(class.class_name)
    ->  from class inner join class_student
    ->  on class.class_id = class_student.class_id
    ->  group by class.class_name
    ->  having count(class.class_name) > 40;

解析:

用到二表内连,生成临时表格后输出class_id,class_name,class_name的数量,其中having语句实现条件人数>40。注意,生成临时表格后,需要使用group by语句才能实现表格内容的分组,否则不能正确输出having后跟的count函数条件

mysql初学,欢迎评论指正拍砖,谢谢!