点滴积累,便是进步!

student(学生信息表):

class(班级信息表):

score(学生成绩表):

需求:查询初一一班所有男生的英语成绩

思路:

  1.明确查询条件:初一一班, 男生, 英语

  2.明确查询结果:成绩

  3.明确要查询的表:student, class, score

  明确这三点以后,剩下的就是如何将条件组合起来。

  试想下,生活中要知道一个学生的某一课程的成绩,首先要明确其班级,然后是其姓名,最后是课程名。

  同理,我们可以通过以下步骤来明确sql:

    ①明确班级:

        因为:student表通过class_id 关联class表,

        所以:select class_id from class where class_name = "初一一班"  ==> 获取该班的 class_id,从而和student表建立关联

    ②明确学生id:

        因为:student表通过stu_id 关联 score表,

        所以:select stu_id from student where sex="M" and class_id =(select class_id from class where class_name= "初一一班") ==> 获取该班级所有男生的stu_id

    ③通过学生id,关联到score表,并添加查询条件,课程名,来查询出成绩

       select stu.stu_name, sco.score from score sco

       left join student stu on sco.stu_id = stu.stu_id

       where stu.sex="M" and stu.class_id = (select class_id from class where class_name= "初一一班") and sco.sub_name="English";

    ④:sql解释:

     

 

posted on 2017-12-29 11:10  菜大中  阅读(1194)  评论(0)    收藏  举报