使用两个字段获取数据库表中的下一行和上一行

时间:2018-08-14 10:56:44

标签: sql

很抱歉,如果我的问题的措词含糊,但我想不出其他措辞。 我有一个数据表,其中包括一个日期列和一个班次列(1、2或3)。假设当前选择了给定的行,我希望能够查询该表的上一条和下一条记录。如果还不够清楚的话,如果当前记录是date = 2018-08-13且shift = 1,那么先前的记录将是2018-08-12 shift3。我快要在表中添加一列了具有日期和班次的连接,但是有更好的方法了! (数据库引擎应该无关紧要,但是我正在使用JavaDB。)

2 个答案:

答案 0 :(得分:0)

这是一种方法。对于上一条记录:

select t.*
from t cross join
     (select t.* from t where t.record = ?) tt
where t.date < tt.date or
      t.date = tt.date and t.shift < tt.shift
order by t.date desc, tt.shift desc
fetch first 1 row only;

下一条记录:

select t.*
from t cross join
     (select t.* from t where t.record = ?) tt
where t.date > tt.date or
      t.date = tt.date and t.shift > tt.shift
order by t.date desc, tt.shift asc
fetch first 1 row only;

请注意,fetch first 1 row only在ANSI / ISO SQL中检索一条记录。某些数据库使用其他语法,例如limitselecct top (1)

答案 1 :(得分:0)

需要更多信息,但是可以使用类似的内容:

async Main() {
    searchCompleteHandler(await searchAndDoSomething(name));  
}

在JavaDB上,我不确定语法...可能类似于:

$( document ).ready(function() {
    $.get({
       url: "/WebProjekat/rest/users",
       success: function(data) {
          //do something with data

       }
    })
    $.get({
       url: "/WebProjekat/rest/articles/mostPopular",
       success: function(data) {
          //do something with data
       }
    })
})
相关问题