SQL查询选择“下一步”记录(类似于第一个或前N个)

前端之家收集整理的这篇文章主要介绍了SQL查询选择“下一步”记录(类似于第一个或前N个)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果某个记录不存在,我需要进行查询以返回下一个(或上一个)记录.例如,请考虑下表:
  1. ID (primary key) value
  2. 1 John
  3. 3 Bob
  4. 9 Mike
  5. 10 Tom.

如果7不存在,我想查询id为7或更大的记录.

我的问题是,

> sql可以使用这些类型的查询吗?
>在DB世界中调用了哪些此类查询

谢谢!

解决方法

是的,这是可能的,但实现将取决于您的RDBMS.

这是它在MysqL,Postgresqlsqlite中的样子:

  1. select ID,value
  2. from YourTable
  3. where id >= 7
  4. order by id
  5. limit 1

在MS sql-Server,Sybase和MS-Access中:

  1. select top 1 ID,value
  2. from YourTable
  3. where id >= 7
  4. order by id

在Oracle中:

  1. select * from (
  2. select ID,value
  3. from YourTable
  4. where id >= 7
  5. order by id
  6. )
  7. where rownum = 1

在Firebird和Informix中:

  1. select first 1 ID,value
  2. from YourTable
  3. where id >= 7
  4. order by id

在DB / 2中(此语法在sql-2008标准中):

  1. select id,value
  2. from YourTable
  3. where id >= 7
  4. order by id
  5. fetch first 1 rows only

在那些具有“窗口”功能的RDBMS中(在sql-2003标准中):

  1. select ID,Value
  2. from (
  3. select
  4. ROW_NUMBER() OVER (ORDER BY id) as rownumber,Id,Value
  5. from YourTable
  6. where id >= 7
  7. ) as tmp --- remove the "as" for Oracle
  8. where rownumber = 1

如果您不确定您拥有哪种RDBMS:

  1. select ID,value
  2. from YourTable
  3. where id =
  4. ( select min(id)
  5. from YourTable
  6. where id >= 7
  7. )

猜你在找的MsSQL相关文章