开发工具与关键技术:PLSQL Developer、Oracle、SQL*plus
一.子查询又叫内查询,就是在一个SQL查询语句内的条件判断时再次进行SQL查询的查询语句。在子查询外面的SQL查询语句一般称为主查询,如下图:
二.在使用子查询的过程中需要注意:
(1)子查询要包含在括号内;
(2)紧跟条件筛选语句(如上图的where语句);
(3)单行操作符对应单行子查询,多行操作符对应多行子查询,如上图的 “in” 属于多行操作符,但由于上图中的子查询是单行子查询,所以 “in” 可换为单行操作符的 “=”。
三.单行子查询只返回一行,使用单行比较操作符;
单行比较操作符:
例如:在employees表中查询出 ‘Kochhar’ 所在部门中每个员工的姓名与部门号。
思路:想要查询这个部门中每个员工的姓名和部门号,就先要知道’Kochhar’所在的是哪个部门,所以可在主查询的条件筛选语句中通过单行操作符的 “=” 接收子查询中查询出来的’Kochhar’所在的那个部门号。
解:select last_name as 姓名,department_id as 部门号
from employees
where department_id = (select department_id as 部门号 from employees where last_name=‘Kochhar’)
子查询执行结果:
主查询执行结果:
如果,将例题改为:在employees表中查询出不与’Kochhar’所在同一部门中每个员工的姓名与部门号。
错误解答:select last_name as 姓名,department_id as 部门号
from employees
where department_id = (select department_id as 部门号 from employees where last_name !=‘Kochhar’)
子查询执行结果:
主查询执行结果:
正确解答:select last_name as 姓名,department_id as 部门号
from employees
where department_id != (select department_id as 部门号 from employees where last_name =‘Kochhar’)
子查询执行结果:
主查询执行结果:
四.多行子查询返回多行,使用多行比较操作符:
多行比较操作符:
例如:(1)在score表中查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录。
错误解答:select sno as 学号,cno as 课程号,degree as 成绩
from score
where cno='3-105’and degree > (select degree as 成绩 from score where sno=109)
子查询执行结果:
主查询执行结果:
正确解答:select sno as 学号,cno as 课程号,degree as 成绩
from score
where cno='3-105’and degree > all (select degree as 成绩 from score where sno=109)
主查询执行结果:
(2)在score表中查询选修编号为“3-105“课程且成绩至少高于选修编号为“3-245”的同学的课程编号、学号和成绩。
(注意:题目中的至少,所以应该用 “any” 比较子查询而不是 “all”)
解:select cno as 课程编号,sno as 学号,degree as 成绩
from score
where cno=‘3-105’ and degree > any (select degree as 成绩 from score where cno=‘3-245’)
子查询执行结果:
主查询执行结果: