当前位置: 移动技术网 > IT编程>开发语言>Java > Oracle不连续的值,如何实现查找上一条、下一条

Oracle不连续的值,如何实现查找上一条、下一条

2018年04月13日  | 移动技术网IT编程  | 我要评论

zobo,山峡之窗,唐子义的原型是谁

1.  遇到的问题

 

已知一个题库,希望实现当前页切换上一题,下一题的需求。

查看得知,数据库中用于查询的字段(主键)是不连续的。如上图所示:stxh为主键number类型。

 

2.  实现方式lead over

2.1  实现代码

   

下一条
select nowId, afterId from( 
SELECT stxh nowId, lead(stxh,1) over (order by stxh) as afterId from EXM_KSTK) 
where afterId-nowId>0 and nowId = 54;

上一条
select beforeId, nowId from( 
SELECT stxh beforeId, lead(stxh,1) over (order by stxh) as nowId from EXM_KSTK) 
where nowId-beforeId>0 and nowId = 54;

 

2.2  lead方法说明

lead(value_expr [,offset][,default]) over([query_partition_clause] order by Order_by_clause)

value_expr:值表达式,通常是字段,也可是是表达式。

offset:偏移,如果>0 表示与当前行相比,向前的行数。默认值为1

default:默认值,偏移结果不存在时,默认的返回值。

 

2.3  分析"实现代码"

以上一条为例吧,主要分析lead over 部分:

SELECT 字段名 beforeId, lead(在字段名,偏移量) over (order by 字段名) as nowId from 表名) 

整条的使用就是需要传入当前的nowId值

 

3.  结合需求完善sql

3.1  上一条(主键stxh)

      首先需要通过当前id获取上一条记录id值

select beforeId from
(SELECT stxh beforeId, lead(stxh,1) over (order by stxh) as nowId from EXM_KSTK) where nowId-beforeId>0 and nowId = 54;

      通过这条sql就拿到上一条的id值了,然后再select查询即可。

SELECT * FROM EXM_KSTK stxh = 
(
  select beforeId from
  (SELECT stxh beforeId, lead(stxh,1) over (order by stxh) as nowId from EXM_KSTK) 
  where nowId-beforeId>0 and nowId = 54
)

 

3.2  下一条(主键stxh)

     直接贴代码吧。

SELECT * FROM EXM_KSTK stxh = 
(
  select  afterId from( 
  SELECT stxh nowId, lead(stxh,1) over (order by stxh) as afterId from EXM_KSTK) 
  where afterId-nowId>0 and nowId = 54
)

 

3.3  补充说明

EXM_KSTK:表名

stxh:我的表主键

54:上文所用到的54就是你需要去传入的当前已知的id值

博客地址:https://www.cnblogs.com/niceyoo

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网