|- 如下以employees表为例:
子查询 (内查询) 在主查询之前一次执行完成。
子查询的结果被主查询(外查询)使用 。
注意:
子查询要包含在括号内。
将子查询放在比较条件的右侧。
单行操作符对应单行子查询,多行操作符对应多行子查询。
--谁的工资比Abel的高
select last_name,salary from employees where salary > (select salary from employees where last_name = 'Abel');
--查询员工名为Chen的manager的信息
select last_name,salary from employees where employee_id = (select manager_id from employees where last_name = 'Chen');
--返回job_id与141号员工相同,salary比143号员工多的员工姓名,job_id 和工资
select last_name,job_id,salary from employees where job_id=(select job_id from employees where employee_id=141)and salary >(select salary from employees where employee_id=143);
--返回公司工资最少的员工的last_name,job_id和salary
select last_name,job_id,salary from employees where salary=(select min(salary) from employees);
--查询最低工资大于50号部门最低工资的部门id和其最低工资
select department_id,min(salary) from employees group by department_id having min(salary)>(select min(salary) from employees where department_id=50);
①多行子查询
在多行子查询中使用 ANY 操作符:
--返回其它部门中比job_id为‘IT_PROG’部门任一工资低的员工的员工号、姓名、job_id 以及salary
select employee_id,last_name,job_id,salary from employees where job_id<>'IT_PROG'and salary < any(select salary from employees where job_id='IT_PROG');
在多行子查询中使用 ALL 操作符:
--返回其它部门中比job_id为‘IT_PROG’部门所有工资低的员工的员工号、姓名、job_id 以及salary
select employee_id,last_name,job_id,salary from employees where job_id<>'IT_PROG'and salary < all(select salary from employees where job_id='IT_PROG');