练习MySQL联表查询时遇到这样一道题

 - 问题: 查询"生物课程"比"物理课程"成绩高的所有学生的相关信息

 - 出错指令: 

 
1 SELECT  student.sid AS '学号', student.sname AS '姓名', course.cname AS '课程', score.num AS '成绩' 
2 FROM student INNER JOIN course INNER JOIN score  
3 ON student.sid=score.student_id AND course.cid=score.course_id AND course.cid=2 
4 WHERE score.num < (SELECT score.num FROM course INNER JOIN score ON course.cid=score.course_id AND course.cid=1);
存在问题的指令

 - 报错信息:

  ERROR 1242 (21000): Subquery returns more than 1 row

 报错信息翻译:

  子查询返回超过1行

 分析与解决方法:

  1. 在重复写入时会出现这种问题, 可通过去掉重复数据解决

    - 通过在写入时加逻辑判断或者外键防止数据重复写入

   2. 利用IN、SOME、ANY、ALL关键字进行限制

    - 报错信息出自子查询, 因此需要对子查询涉及指令进行条件修改

 - 最终解决指令:

 
1 SELECT  student.sid AS '学号', student.sname AS '姓名', course.cname AS '课程', score.num AS '成绩'
2 FROM student INNER JOIN course INNER JOIN score
3 ON student.sid=score.student_id AND course.cid=score.course_id AND course.cid=2 
4 WHERE score.num < ANY(SELECT score.num FROM course INNER JOIN score ON course.cid=score.course_id AND course.cid=1);
最终解决指令

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-11
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
猜你喜欢
  • 2021-05-31
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2021-12-18
  • 2022-01-02
相关资源
相似解决方案