您的位置:首页 > 数据库 > Oracle

oracle子查询

2016-02-26 10:21 716 查看
子查询:在一个查询的内部包含另外一个查询。

普通子查询

-- 查询出比7654工资还高的所有雇员的信息
select * from emp e where e.sal > (select sal from emp where empno = 7654);

-- 查询出工资比7654高,同一时候与7788从事同样工作的所有雇员的信息
select * from emp e
where e.sal > (select sal from emp where empno = 7654)
and e.job = (select job from emp where empno = 7788);

-- 查询出工资最低的雇员姓名、工作、工资
select e.ename, e.job, e.sal from emp e
where e.sal = (select min(sal) from emp);


in 查询

in keyword用来匹配一个集合中的记录

-- 查询雇员编号为1234,2345,7369,7900的雇员信息
select * from emp where empno in(1234, 2345, 7369, 7900);




-- 查询雇员编号不是 1234,2345。7369,7900的雇员信息
select * from emp where empno not in(1234, 2345, 7369, 7900);




-- 查询每一个部门的最低工资相应的员工信息
select * from emp where sal in (select min(sal) from emp group by deptno);




anykeyword

any:表示随意的。

< any
比子查询返回的随意一个结果小就可以,即小于返回结果的最大值

= any
和子查询中随意一个结果相等就可以。相当于in

> any
比子查询返回的随意一个结果大就可以,即大于返回结果的最小值

-- 查询每一个部门的最低工资
select min(sal) min_sal from emp group by deptno;




sal 大于 any (每一个部门最低工资),即大于返回结果的最小值

select * from emp where sal > any (select min(sal) from emp group by deptno);




sal = any (每一个部门最低工资),即 和子查询中每一个结果相等,同in

select * from emp where sal = any (select min(sal) from emp group by deptno);




sal < any (每一个部门最低工资)。即大于返回结果的最大值

select * from emp where sal < any (select min(sal) from emp group by deptno);




allkeyword

all:表示全部的。

< all
比子查询返回的全部的结果都小,即小于返回结果的最小值

> all
比子查询返回的全部的结果都大,即大于返回结果的最大值

= all
无意义。逻辑上也不成立

查询工资在2000 到 3500的工资段的工资集合

select distinct sal from emp where sal between 2000 and 3500;




> all (工资在2000 到 3500的工资段的工资集合) ,即大于最大值

select * from emp where sal > all(select distinct sal from emp where sal between 2000 and 3500);




< all (工资在2000 到 3500的工资段的工资集合),即小于最小值

select * from emp where sal < all(select distinct sal from emp where sal between 2000 and 3500);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: