Oracle中子查询

1.单行子查询
select * from emp
where sal > (select sal from emp where empno > 7876);

2.子查询空值/多值问题
如果子查询未返回任何行,则主查询也不会返回任何结果。
(空值)select * from emp where sal >(select sal from emp where empno=6666);

如果子查询返回单行结果,则为单行子查询,可以在主查询中对其使用相应的单行记录比较运算符
(正常)select * from emp
where sal > (select sal from emp where empno > 7876);

如果子查询返回多行结果,则为多行子查询,此时不允许对其使用单行记录比较运算符
(多值)select * from emp where sal > (select avg(sal) from emp group by deptno);--非法

3.多行子查询
select * from emp where sal > any(select avg(sal) from emp group by deptno);
注:any(collection) 函数.  只要大于collection中任意一个即满足>条件。与in用法类似
select * from emp where sal > all(select avg(sal) from emp group by deptno);
注:all(collection)函数,比子查询返回结果中的所有值都大才满足>条件。
select * from emp where job in (select job from emp where ename = 'Smith' or ename = 'Halen');

4.TopN查询
select * from emp where rownum = 1 or rownum = 2;
排序,列出所有记录或前N条记录
select * from (select * from emp order by sal desc) 
where rownum <= 5;--rownum只能是小于等于”<=”n.

排序,列出指定区间的记录(下面的查询语句执行后不会有任何结果。)
select 字段列表
from   (select 字段列表 from 表名 order by 排序字段)
where rownum>=11 and rownum<=15;

如果想实现大于等于,或者between,则如下代码:
select 字段列表 from
(select rownum num, 字段列表 from 表名 order by 排序字段)
where num >= 8 and num <=16;

原因分析:rownum是查询过后才按顺序排的,假如你的条件是rownum>1;那么返回数据的第一条(rownum是1)就不符合要求了,
然后第二条数据变成了现在的第一条,结果这一条rownum又变成1了又不符合要求了,以此类推 就没有返回结果。

5.分页查询
通过第4点对rownum的理解之后,就可以写出我们想要的分页语句了。
仍然不清楚的,可以先去了解一下Oracle伪列rownum,rowid
select 字段列表
from (select rownum no,t.* from table_name t)
where no > 2 and no < 5;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值