MySql 三表联查 查询数学成绩比语文成绩高的所有学生信息

要求:
查询所有学生信息(数学成绩比语文成绩高)

表格信息

表架构

这里写图片描述

表1:student

这里写图片描述

表2:course

这里写图片描述

表3:studeng_course

这里写图片描述

解题思路

查询逻辑流程图
这里写图片描述

1.查询数学和语文id

数学和语文的id位于course表中,所以要到course表中查询

select id from course where name='数学';
select id from course where name='语文';

2.查询学生id和对应课程分数

根据上面查到的id,到student_course表中查询语文和数学的学生id以及语文成绩、数学成绩

-- 查询选课语文的学生信息和分数
select * from student_course 
    where course_id =(select id from course where name='语文')
-- 查询选课语文的学生信息和分数
select * from student_course
    where course_id=(select id from course where name='数学')
**查询结果:**

这里写图片描述

3.查询满足条件的学生信息

根据tempChinese, tempMath和student三个表去查询满足数学成绩比语文成绩高的学生信息,此处代码不可能一次写完,下面我分几个步骤(答案是第三步
第一步:查询满足学生id都一样,以及数学成绩>语文成绩

select * from 
student,
tempChinese,
tempMath 
    where student.id=tempChinese.student_id -- student表中学生id=tempChinese表中的学生id
    and tempChinese.student_id=tempMath.student_id -- tempChinese表中学生id=tempMath表中学生id
    and tempMath.score>tempChinese.score --数学成绩>语文成绩

第二步:将上面代码的别名表用代码赋值

select * from 
    student,
        (select * from student_course 
            where course_id =(select id from course where name='语文'))as tempChinese,
        (select * from student_course
            where course_id=(select id from course where name='数学'))as tempMath
        where student.id=tempChinese.student_id
        and tempChinese.student_id=tempMath.student_id
        and tempMath.score>tempChinese.score

查询结果:
这里写图片描述

第三步:上面的查询结果,不方面阅读,我们需要在select 后面的*号改成我们需要的信息(学生信息,数学成绩,语文成绩)
下面代码中student.* 的意思是student中所有字段

    select student.* , tempMath.score as 数学, tempChinese.score as 语文 from 
    student,
        (select * from student_course 
            where course_id =(select id from course where name='语文'))as tempChinese,
        (select * from student_course
            where course_id=(select id from course where name='数学'))as tempMath
        where student.id=tempChinese.student_id
        and tempChinese.student_id=tempMath.student_id
        and tempMath.score>tempChinese.score

结果:

这里写图片描述

  • 10
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值