SQL面试题

题目描述

学生表(STUDENT)

ID(pk)STUDENT_NOSTUDENT_NAME
11001王明
21002李涛
31003刘雨
41004赵欢

成绩表(SCORE)

ID(pk)STUDENT_ID(fk)CLASS_NAMESCORE
11语文90
21数学90
31英语90
42语文60
52数学60
62英语60
73语文70
83数学70
93英语70
104语文80
114数学80
124英语80

学生表主键(ID)对应 成绩表外键(STUDENT_ID)
请使用SQL统计出总分数超过200的学生,并按总分数进行排名

输出结果格式如下

STUDENT_NOSTUDENT_NAMETOTAL_SCORE
1001王明270
1004赵欢240
1003刘雨210

SQL解答

SELECT stu.student_no, stu.student_name ,SUM(sc.score) total_score

FROM student stu 

LEFT JOIN score sc ON stu.id= sc.student_id 

GROUP BY stu.student_no,stu.student_name HAVING total_score>200

ORDER BY total_score desc;

这样的一道SQL题,融合了 LEFT JOIN、GROUP BY、HAVING、ORDER BY、DESC等,算是比较综合的一道题目

其中考察点是主键与外键的关联(外连接)、分组之后的过滤(GROUP BY、HAVING、对结果排序(升序降序)


易错点

易错点1

GROUP BY stu.student_no

如果SQL写成如下

SELECT stu.student_no, stu.student_name ,SUM(sc.score) total_score

FROM student stu 

LEFT JOIN score sc ON stu.id= sc.student_id 

GROUP BY stu.student_no HAVING total_score>200

ORDER BY total_score desc;
报错信息如下:

1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘demo.stu.student_name’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by, Time: 0.001000s

原因是分组时,需要使用

GROUP BY stu.student_no,stu.student_name


易错点2

WHERE total_score>200

如果SQL写成如下

SELECT stu.student_no, stu.student_name ,SUM(sc.score) total_score

FROM student stu 

LEFT JOIN score sc ON stu.id= sc.student_id WHERE total_score>200

GROUP BY stu.student_no,stu.student_name

ORDER BY total_score desc;

总分数超过200这个条件是基于分组之后的条件,很多人把这个条件放到了 where 子句之后,也是不对的

报错信息如下:

1054 - Unknown column ‘total_score’ in ‘where clause’, Time: 0.000000s

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上尤流苏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值