Oracle不连续的值,如何实现查找上一条、下一条
生活随笔
收集整理的這篇文章主要介紹了
Oracle不连续的值,如何实现查找上一条、下一条
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
總結
以上是生活随笔為你收集整理的Oracle不连续的值,如何实现查找上一条、下一条的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 抖动提示动画
- 下一篇: Zabbix的安装(源码安装)