且构网

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

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

更新时间:2023-01-20 23:42:31

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



在MySQL,PostgreSQL和SQLite中的样子:

 从YourTable中选择ID 
id> = 7
order by id
limit 1

-Server,Sybase和MS-Access:

 从YourTable中选择前1个ID,值
id> = 7
order by id

在Oracle中:

  select * from(
选择ID,值
来自YourTable
其中id> = 7
order by id

其中rownum = 1



在Firebird和Informix中:

 从YourTable中选择前1个ID,值

其中id> = 7
在DB / 2中(此语法在SQL-2008标准中):
 从YourTable中选择id,值

其中id> = 7
order by id
fetch first 1 rows only



在这些具有窗口函数的RDBMS中标准):

 选择ID,值
从(
选择
ROW_NUMBER (ORDER BY id)as rownumber,
Id,Value
from YourTable
其中id> = 7
)as tmp ---删除Oracle的as
where rownumber = 1

如果你不确定你有哪个RDBMS:

 从YourTable中选择ID,值

其中id =
(select min(id)
from YourTable
where id> = 7


I need to do a query to return the next (or prev) record if a certain record is not present. For instance consider the following table:

ID (primary key)    value
1                    John
3                    Bob
9                    Mike
10                   Tom.

I'd like to query a record that has id 7 or greater if 7 is not present.

My questions are,

  1. Are these type of queries possible with SQL?
  2. What are such queries called in the DB world?

Thanks!

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

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

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

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

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

In Oracle:

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

In Firebird and Informix:

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

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

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

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
      )