4.6子查询
where(这个值是计算出来的) 本质:在where语句中嵌套一个子查询语句 where(select*from) ?? ?? – 1、查询 数据库结构-1 得所有考试结果(学号,科目编号,成绩),降序排列 – 方式一:连接查询 SELECT studentno ,r.subjectno ,studentresult FROM result r INNER JOIN subject sub ON r.subjectno = sub.subjectno WHERE subjectname = ‘数据库结构-1’ ORDER BY studentresult DESC
– 方式二:使用子查询(由里及外的) SELECT studentno ,subjectno ,studentresult FROM result WHERE subjectno = ( SELECT subjectno FROM subject WHERE subjectname = ‘数据库结构-1’ ) ?? ?? – 练习 2、查询高等数学-1的分数不小于80的学生的学号和姓名
– 方式一:连接查询 SELECT DISTINCT s.studentno ,studentname FROM student s INNER JOIN result r ON s.studentno = r.studentno INNER JOIN subject sub ON sub.subjectno = r.subjectno WHERE subjectname = ‘高等数学-1’ AND studentresult>=80
– 方式二:子查询 SELECT DISTINCT s.studentno ,studentname – distinct去重 FROM student s INNER JOIN result r ON r.studentno = s.studentno WHERE studentresult >=80 AND subjectno = ( SELECT subjectno FROM subject WHERE subjectname = ‘高等数学-1’ )
– 方式三:嵌套查询 SELECT studentno,studentname FROM student WHERE studentno IN ( SELECT studentno FROM result WHERE studentresult>=80 AND subjectno = ( SELECT subjectno FROM subject WHERE subjectname = ‘高等数学-1’ ) )
?? ?? 遇到的问题:
子查询返回超过1行
- 分析与解决方法:
1. 在重复写入时会出现这种问题, 可通过去掉重复数据解决
- 通过在写入时加逻辑判断或者外键防止数据重复写入
|