比如获得指定id=123的纪录,同时还要获得按id排序的前面和后面的纪录,用一次查询
排完序后:
id
111
123
124
125要获得id=123的前后两条纪录,也就是111和124,该怎么写sql语句?

解决方案 »

  1.   

    select * from tablename a
    where id = (select max(id) from tablename where id < a.id)
       or id = (select min(id) from tablename where id > a.id)
      

  2.   

    SELECT *
    FROM table1
    WHERE id-123 BETWEEN -2 AND 2
      

  3.   

    (select max(id) from tablename a where a.id<123)
    union all
    (select min(id) from tablename a where a.id>123)
      

  4.   

    create table T(id int)
    insert T select 111
    union all select 123
    union all select 124
    union all select 125select id=max(id) from T where id<123
    union all 
    select id from T where id=123
    union all 
    select min(id) from T where id>123
      

  5.   

    select top 1 id from tablename where id < 123 order by id DESC
    select top 1 id from tablename where id > 123 order by id ASC