dpbe81245 2013-12-03 02:59
浏览 432

如何获取sql中的下一行

I have a table that is something like this

id  |  names  |  value  
1     Vicky       43
2     Erica       23
3     Rueben      33
4     Bob         54
5     Chris       60

Then I set them in order according to their value. Now the table looks like this.

id  |  names  |  value  
5     Chris       60
4     Bob         54
1     Vicky       43
3     Rueben      33
2     Erica       23

Now the starting point is id 5 which has a name of Chris and a value of 60. My goal is, to get the next row which has an id of 4 and name of Bob and a value of 54.

  • 写回答

4条回答 默认 最新

  • duan3601 2013-12-03 03:02
    关注

    You just need to limit the resultset:

    SELECT * from table
    ORDER BY value DESC
    LIMIT 1, 1
    

    Output:

    | ID | NAMES | VALUE |
    |----|-------|-------|
    |  4 |   Bob |    54 |
    

    Fiddle here.

    The LIMIT basically works this way: the first number sets the starting point (being 0 the minimal value) and the second number the amount of items to fetch (in this case only one).

    Edit:

    A different way of understanding the question would be: Given a value for a particular field (EG: id field with value of 5)... what would be the previous record? As we have the id 4 in the data we should return that one.

    That could be accomplished this way:

    SELECT * from t
    WHERE id < 5
    ORDER BY id DESC
    LIMIT 1
    

    Fiddle here.

    This way you can traverse the results in both orders (ASC and DESC) and also get both the next or previous (> or <) rows.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示