mysql复杂查询—学生-课程-成绩

博客围绕学生、教师、课程和成绩表,给出多个MySQL查询示例。包括查询总成绩小于60的学生、李老师个数、同学选课数和总成绩等,还涉及课程平均成绩、特定课程学生成绩等查询,提供了具体SQL语句及部分问题的解决思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    学生表:id  name 

    教师表:   id  name

    课程表:   id  name  teacher_id

    成绩表:   student_id   course_id     score

1.查询总成绩小于60的学生id以及姓名                            (根据用户分组 通过having对平均成绩进行筛选)

     select sc.student_id,st.name ,sum(score) total from score sc
     left join student st on st.id=sc.student_id 
     left join course c on c.id=sc.course_id group by sc.student_id 
     having total<60

2.查询李老师的个数

     select count(*) from teacher where name like '李%';

3.查询所有同学的学号、姓名、选课数、总成绩 

     select st.id,st.name ,count(course_id) total_course,sum(score) total_score from student st
     left join score sc  on st.id=sc.student_id
     left join course c on c.id = sc.course_id
     group by st.id

(有反映这条sql有问题,直接复制确实会执行不了,只要去掉中间的空格就好了,然后又改了一下)

       select st.id,st.name,count(course_id) total_course,sum(ifnull(score,0)) total_score from student st left join score sc on st.id=sc.student_id left join course c on c.id = sc.course_id group by st.id

4.查询每门课程的平均成绩,结果按平均成绩升序排列,平均成绩相同时,按课程号降序排列;

     select sc.course_id,c.name,avg(score) score from score sc 
     left join course c on sc.course_id=c.id group by sc.course_id
     order by score ,c.id desc

5.查询课程名称为“数学”,且分数低于60的学生姓名和分数

     select st.id,st.name from score sc
     left join course c on c.id=sc.course_id
     left join student st on st.id=sc.student_id
     where c.name="数学" and score<60

6.求选了课程的人数

     select count(distinct(student_id)) from score

7. 检索至少选修两门课程的学生学号

    select student_id,count(student_id) course ,score from score group by student_id having course>=2 

8.查询全部学生都选修的课程的课程号和课程名(从学生表中统计出学生总数,在成绩表中根据课程分组,选择每门课程的人数等于学生总数)

     select sc.course_id,c.name,count(student_id) num from score sc
     left join course c on c.id=sc.course_id
     left join student st on st.id=sc.student_id
     group by sc.course_id
     having num=(select count(*) from student)

9查询“语文”课程比“数学”课程成绩高的所有学生的学号;

思路: (1)获取所有选了语文课程的学生的成绩(学号,成绩) --临时表

      (2)获取所有选了数学课程的学生的成绩(学号,成绩) --临时表

   (3)根据学号连接两张临时表(学号,语文成绩,数学成绩),加条件进行查询

     select a.student_id,yuwen 语文,shuxue 数学 from
     (select sc.student_id,sc.score yuwen from score sc
     left join course c on c.id=sc.course_id
     where c.name="语文") as a
     left join(select sc.student_id,sc.score shuxue from score sc
     left join course c on c.id=sc.course_id
     where c.name="数学") as b 
     on a.student_id=b.student_id where yuwen> if(isnull(shuxue),0,shuxue);

 

来源:http://www.cnblogs.com/tomato0906/articles/7414142.html

 

 

   

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值