Oracle子查询简单介绍

1,查询和tom同一部门且比他工资低的员工姓名和工资:
select ename,sal from emp where deptno=(select deptno from emp
where ename = 'tom')and sal< (select sal from emp where ename = 'tom');

2,查询工资最高的员工名字和工资:
select ename,sal from emp where sal=(select max(sal) from emp);

3,查询所有比tom工资高的员工信息:
select * from emp where sal>(select sal from emp where ename = 'tom');

4,查询工资高于平均工资的员工名字和工资:
select ename,sal from emp where sal>(select avg(sal) from emp);


5,使用in关键字:查询员工编号为1001,1002,1003的员工信息
select * from emp where empno in(1001,1002,1003);


6,使用not in关键字:查询员工编号不是1001,1002,1003的员工信息
select * from emp where empno not in(1001,1002,1003);


7,使用any关键字:< any 比子查询返回的任意一个结果小即可,即小于返回结果的最大值,

= any 和子查询中任意一个结果相等即可,相当于in, > any 比子查询返回的任意一个结果大即可,即大于返回结果的最小值。

    查询每个部门的最低工资:  
    select min(sal) min_sal from emp group by deptno;
    此时使用:> any(大于最小值)
    select * from emp where sal > any (select min(sal) from emp group by deptno);

    此时使用:= any(即和子查询中每个结果相等)
    select * from emp where sal = any (select min(sal) from emp group by deptno);

    此时使用:< any(小于最大值)
    select * from emp where sal < any (select min(sal) from emp group by deptno);  


8,使用all关键字:< all 比子查询返回的所有的结果都小,即小于返回结果的最小值,

> all 比子查询返回的所有的结果都大,即大于返回结果的最大值, = all 无意义,逻辑上也不成立。

    查询工资在2000到3500的工资段集合:
    select distinct sal from emp where sal between 2000 and 3500;

    此时使用:> all(即大于最大值3500)
    select * from emp where sal > all(select distinct sal from emp where sal between 2000 and 3500);

    此时使用:< all(即大于最小值2000)
    select * from emp where sal < all(select distinct sal from emp where sal between 2000 and 3500);

猜你喜欢

转载自blog.csdn.net/LittleMangoYX/article/details/80267034