不相关子查询:
--子查询先执行,然后再执行外部查询。外部查询会使用到子查询的
--返回值。
--查询挣得的比亚伯多的雇员的姓名和薪水
select last_name,salary
from employees
where salary > (select salary
from employees
where last_name='Abel');
--子查询可以放在比较操作符的左边,但是这样写可读性很差
select last_name,salary
from employees
where (select salary
from employees
where last_name='Abel') < salary;
--单行子查询:
--子查询返回单行单列一个值
--多行子查询:
--子查询返回多行单列多个值
--对于单行子查询的返回值,在外部查询要使用单行比较操作符
--进行比较:=、>,<,<=,>=
--查找和Chen干同样的工作,但是挣得比Chen多的雇员的信息
select last_name,job_id,salary
from employees
where job_id = (select job_id
from employees
where last_name='Chen')
and salary > (select salary
from employees
where last_name='Chen');
--子查询中也可以用组函数
--本例显示了月薪等于最低月薪的雇员的姓名、工作编号和月薪
select last_name,job_id,salary
from employees
where salary = (select min(salary)
from employees);
--注意,如果子查询返回的结果集为空,那么会把null值带入到
--外部查询中,这可能会导致外部查询的结果集也为空
select last_name,salary
from employees
where job_id = (select job_id
from employees
where last_name='Haas');
--对于多行子查询,在外部查询中要比较这些值,必须
--使用多行比较操作符:3个:in any all
--其中,any all不能单独用,在其前面必须加上单行比较操作符。
--例如:<any >any=any <all >all等
--本例显示了工作不是IT程序员,
--并且工资少于任何一个程序员的雇员的信息
select last_name,salary
from employees
where salary <any (select salary
from employees
where job_id='IT_PROG')
and job_id <> 'IT_PROG';
--本例显示了工作不是IT程序员,
--并且工资少于所有程序员的雇员的信息
select last_name,salary
from employees
where salary <all (select salary
from employees
where job_id='IT_PROG')
and job_id <> 'IT_PROG';
--当外部查询的where条件使用not in 操作符时,要特别
--注意:如果子查询的返回值中有一个null值,会导致
--外部查询的where条件也为null,从而外查询的结果集为空
--查询所有普通雇员(没有当官的)的姓名
select last_name
from employees
where employee_id not in (selectmanager_id
from employees);
--解决办法:排除子查询结果集中的null值
select last_name
from employees
where employee_id not in (selectmanager_id
from employees
where manager_idis not null);