总结一下multiple-row子查询中in、any、all的用法
Operator
Meaning
IN
Equal to any member in the list
ANY
Compare value to each value returned by
the subquery
ALL
Compare value to every value returned
by the subquery
IN:使用in时,会与子查询中的每一个值进行比较,与任意一个值相同就会被返回,例:
select last_name,salary,department_id
from employees
where salary in(select min(salary)
from employees
group by department_id);
会返回工资为每个部门最低工资的雇员。
ANY:any操作符将一个值与子查询中的每一个只进行比较。
>any可以理解为大于子查询中返回的任意一个值,因此只要大于最小值即可
看下面这个例子:
select salary
from employees
where job_id = 'IT_PROG'
接着执行这个查询:
select employee_id,last_name,job_id,salary
from employees
where salary < any (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
通过返回结果可以看到,没有任何人的工资大于最高值9000,因此
我们把上面的sql稍作修改,any:
select employee_id,last_name,job_id,salary
from employees
where salary > any (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
可以看到,返回的结果中最低工资大于IT_PROG部门的最低工资4200元,因此>any返回的结果是大于子查询中的最大值。
=any:表示等于子查询中返回的任意一个值
select employee_id,last_name,job_id,salary
from employees
where salary = any (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'
order by salary asc;
可以看到,返回的结果与子查询中的salary的数据一致,=any操作符相当于in
<>any
select employee_id,last_name,job_id,salary
from employees
where salary <> any (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'
order by salary asc;
返回的结果中包含子查询中的值,也包含不属于子查询中的值
ALL:all操作符与子查询中返回的全部值进行比较
由于all代表全部,所以all表示大于子查询中返回全部值中的最大值。
我们继续把上面的sql进行一下修改:
select employee_id,last_name,job_id,salary
from employees
where salary < all (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'
order by salary desc;
IT_PROG部门中最低工资为4200,可以看到,返回的结果小于4200最小值,因此
再将all看一下结果
select employee_id,last_name,job_id,salary
from employees
where salary > all (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'
order by salary asc;
从结果中可以看到,返回的结果均大于IT_PROG部门最高工资9000。因此>all表示大于子查询中返回全部结果的最大值。
=all 等于子查询中返回的全部值,这种情况下一般整个查询没有返回结果
<>all 表示不等于子查询中的所有值,相当于not in操作符
select employee_id,last_name,job_id,salary
from employees
where salary <> all (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'
order by salary asc;
由于结果太多,不再贴出返回结果,从结果中可以看出<>all相当于not in操作,但是比起not in操作又有一定的优势,会在下一篇文章中描述。