Oracle中的伪列
一. rownum
1.rownum等于某值时的查询条件:只有rownum = 1,有数据显示。rownum = n(n>2)没有数据,如果想要实现,则可以搭配子查询使用
1 | select a.*,rownum from emp where rownum =1; |
2.rownum大于某值时的查询条件:Oracle对于rownum >= n这个条件是不成立的,即使是n =1,也没有任何数据返回。想要实现这一功能,需要利用子查询来完成。
1 | select * from ( select a.*,rownum rn from emp a) b where b.rn >=3; |
3.rownum小于某值时的查询条件:rownum <= n 是成立的,所以有返回值。
1 | select a.*,rownum from emp a where rownum <=3; |
4.rownum和order的搭配使用:rownum在和order搭配使用时,一定要注意顺序,因为rownum的优先级是大于order的。所以在两者搭配使用时,要做到先排序,再取行号。
1 | select * from ( select a.* from emp a order by sal) b where rownum <= 3; |
5.rownum,order和子查询搭配使用,实现排序后,取第几行数据的功能
1 2 3 4 5 6 | #取emp表工资第二高的员工 select c.* from ( select b.*,rownum as rn from ( select a.* from emp a order by sal desc ) b) c #先排序,在排行号,最后取行号 where c.rn = 2; |
6.使用rownum分页查询
1 2 3 4 | # 假设每页n行,a为页数 select * from ( select a.*,rownum as rn from emp a) b where rn between &a*n-(n-1) and &a*n; |
二. rowid
1. 使用rowid来删除重复数据
1 2 3 4 5 6 | # 准备数据,创建一个空表emp1,结构和emp表一样,将emp表中10部门的数据重复插入到emp1表中 insert all when deptno = 10 into emp1(empno,ename,job,mgr,hiredate,sal,comm,deptno) values (empno,ename,job,mgr,hiredate,sal,comm,deptno) select * from emp; # 利用聚合函数和rowid删除重复数据 delete from emp1 where rowid not in ( select max (rowid) from emp1 group by deptno); |
三. level
1. 与connect by结合使用实现树形查询
level在其中的作用是控制节点和显示节点深度,而且level是自增的,所以需要connect by来控制level的取值范围。
语法:
select
from table_name
where [level = ?] --控制节点
start with condition --选择开始的节点
connect by prior 上级=下级/下级=上级
1 2 3 4 5 6 7 | # 查询出雇员表中KING的下级的下级 select ename, level from emp where level = 3 start with ename = 'KING' connect by prior empno = mgr order siblings by sal; |
2. 利用level自增的性质,显示多条数据
1 2 3 4 5 | # 显示1-100之间的所有偶数 seelct level from dual where mod( level ,2) = 0 connect by <=100; |
3. 与日期函数结合使用,打印出符合条件的日期
1 2 3 4 5 | # 查询本年所有的星期一 select next_day(trunc(sysdate, 'yyyy' )-1, '星期一' ) + ( level -7) from dual where mod( level ,7) = 0 connect by level <= to_char(last_day(add_months(trunc(sysdate, 'yyyy' ),11)), 'ddd' ); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~