Oracle不连续的值,如何实现查找上一条、下一条
1.? 遇到的問(wèn)題
?
已知一個(gè)題庫(kù),希望實(shí)現(xiàn)當(dāng)前頁(yè)切換上一題,下一題的需求。
查看得知,數(shù)據(jù)庫(kù)中用于查詢的字段(主鍵)是不連續(xù)的。如上圖所示:stxh為主鍵number類型。
?
2.? 實(shí)現(xiàn)方式lead over
2.1? 實(shí)現(xiàn)代碼
? ?
下一條 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方法說(shuō)明
lead(value_expr [,offset][,default]) over([query_partition_clause] order by Order_by_clause)
value_expr:值表達(dá)式,通常是字段,也可是是表達(dá)式。
offset:偏移,如果>0 表示與當(dāng)前行相比,向前的行數(shù)。默認(rèn)值為1
default:默認(rèn)值,偏移結(jié)果不存在時(shí),默認(rèn)的返回值。
?
2.3? 分析"實(shí)現(xiàn)代碼"
以上一條為例吧,主要分析lead over 部分:
SELECT 字段名 beforeId, lead(在字段名,偏移量) over (order by 字段名) as nowId from 表名)整條的使用就是需要傳入當(dāng)前的nowId值
?
3.? 結(jié)合需求完善sql
3.1? 上一條(主鍵stxh)
? ? ? 首先需要通過(guò)當(dāng)前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;
? ? ? 通過(guò)這條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? 補(bǔ)充說(shuō)明
EXM_KSTK:表名
stxh:我的表主鍵
54:上文所用到的54就是你需要去傳入的當(dāng)前已知的id值
博客地址:https://www.cnblogs.com/niceyoo
總結(jié)
以上是生活随笔為你收集整理的Oracle不连续的值,如何实现查找上一条、下一条的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android 抖动提示动画
- 下一篇: Zabbix的安装(源码安装)