What is the SQL for 'next' and 'previous' in a table?

后端 未结 7 890
抹茶落季
抹茶落季 2020-12-05 12:21

I have a table of items, each of which has a date associated with it. If I have the date associated with one item, how do I query the database with SQL to get the \'previous

7条回答
  •  广开言路
    2020-12-05 12:25

    My own attempt at the set solution, based on TheSoftwareJedi.

    First question:

    select date from test where date = 8
    union all
    select max(date) from test where date < 8
    union all
    select min(date) from test where date > 8
    order by date;
    

    Second question:

    While debugging this, I used the data set:

    (key:date) 1:1,2:3,3:8,4:8,5:19,10:19,11:67,15:45,16:8,17:3,18:1
    

    to give this result:

    select * from test2 where date = 8
    union all
    select * from (select * from test2
                       where date = (select max(date) from test2 
                                         where date < 8)) 
        where key = (select max(key) from test2 
                        where date = (select max(date) from test2 
                                          where date < 8))
    union all
    select * from (select * from test2
                       where date = (select min(date) from test2 
                                         where date > 8)) 
        where key = (select min(key) from test2 
                        where date = (select min(date) from test2 
                                          where date > 8))
    order by date,key;
    

    In both cases the final order by clause is strictly speaking optional.

提交回复
热议问题