且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-20 22:18:25

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

Yes, it's possible, but implementation will depend on your RDBMS.

这是在 MySQL、PostgreSQL 和 SQLite 中的样子:

Here's what it looks like in MySQL, PostgreSQL and SQLite:

select ID, value
from YourTable
where id >= 7
order by id
limit 1

在 MS SQL-Server、Sybase 和 MS-Access 中:

In MS SQL-Server, Sybase and MS-Access:

select top 1 ID, value
from YourTable
where id >= 7
order by id

在甲骨文中:

select * from (
    select ID, value
    from YourTable
    where id >= 7 
    order by id
)
where rownum = 1

在 Firebird 和 Informix 中:

In Firebird and Informix:

select first 1 ID, value
from YourTable
where id >= 7
order by id

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

In DB/2 (this syntax is in SQL-2008 standard):

select id, value
from YourTable
where id >= 7
order by id
fetch first 1 rows only

在那些具有窗口"功能的 RDBMS 中(在 SQL-2003 标准中):

In those RDBMS that have "window" functions (in SQL-2003 standard):

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

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

And if you are not sure which RDBMS you have:

select ID, value
from YourTable
where id = 
      ( select min(id)
        from YourTable
        where id >= 7
      )