oracle 子查询

1. 子查询所要解决的问题:不能一步求解

 2.注意的问题

     2.1where,select,having,from使用子查询

--select
select empno,sal,(select job from emp where empno =7389) 第四列
from emp;      

--having,聚合函数用having
select deptno,min(sal)
from emp   
group by deptno
having min(sal)> (select min(sal) from emp where deptno =10)  

--from
select * 
from (select empno,ename,sal from emp)

   2.2 不可以在group by 后面使用子查询

   2.3 sql 优化:尽量使用多表查询

   
--查询部门名称是sales 的员工

--子查询(访问数据库2次)   select *   from emp where deptno = (select deptno from dept where dname='SALES') --多表查询(访问数据库1次)   select e.* from emp e,dept d where e.deptno =d.deptno and d.dname ='SALES'

 2.4一般不再子查询中排序;但在top-n 分析问题中,必须对子查询排序

  oracle 10g 当中没有top关键字

   2.5一般先执行子查询,在执行主查询;但相关子查询例外

   2.6 多行子查询:in,any(大于集合当中最小值),all(大于集合当中最大值)

  --in 在集合中,查询部门名称为sales和accounting员工
  select * 
  from  emp
  where deptno in(select deptno from dept where  dname='SALES' or dname='ACCOUNTING');
   --any 和集合中任意一个值进行比较(最小值)
  --查询工资比30号部门任意一个员工高的员工信息
  select * 
  from emp
  where sal> any (select sal from emp where deptno=30);
  --all所有值进行比较,比30号部门员工所有的员工高的员工信息
  select * 
  from emp
  where sal > all (select sal from emp where deptno=30)
  ====
  select * 
  from emp
  where sal > (select max(sal) from emp where deptno=30)

   2.7 多行子查询中的null

  --not in
  --分析:主体还是查询员工,含有mgr 这一列的才是老板的员工,not in 当中只能查询不包含null的
  --查询不是老板的员工
  select * 
  from emp
  where empnoo not in (select mgr from emp where mgr is not null);
  --查询是老板的员工
  select * 
  from emp
  where empnoo  in (select mgr from emp);

 

转载于:https://www.cnblogs.com/glblog/p/5782578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值