zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SSM商城项目(二)
    SSM商城项目(一)
    Solr
    Lucene
    TP5分页函数paginate中的each()传参
    微信小程序+php 授权登陆,完整代码
    thinkphp5 + barcode 生成条形码
    微信小程序-获取当前位置和城市名
    PHP查询附近的人及其距离的实现方法
    thinkphp5连接sql server
  • 原文地址:https://www.cnblogs.com/niceyoo/p/8811179.html
Copyright © 2011-2022 走看看