[英]SQL Query to Select the 'Next' record (similar to First or Top N)
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. 如果7不存在,我想查询id为7或更大的记录。
My questions are, 我的问题是,
Thanks! 谢谢!
Yes, it's possible, but implementation will depend on your RDBMS. 是的,这是可能的,但实现将取决于您的RDBMS。
Here's what it looks like in MySQL, PostgreSQL and SQLite: 这是它在MySQL,PostgreSQL和SQLite中的样子:
select ID, value
from YourTable
where id >= 7
order by id
limit 1
In MS SQL-Server, Sybase and MS-Access: 在MS SQL-Server,Sybase和MS-Access中:
select top 1 ID, value
from YourTable
where id >= 7
order by id
In Oracle: 在Oracle中:
select * from (
select ID, value
from YourTable
where id >= 7
order by id
)
where rownum = 1
In Firebird and Informix: 在Firebird和Informix中:
select first 1 ID, value
from YourTable
where id >= 7
order by id
In DB/2 (this syntax is in SQL-2008 standard): 在DB / 2中(此语法在SQL-2008标准中):
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): 在那些具有“窗口”功能的RDBMS中(在SQL-2003标准中):
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: 如果您不确定您拥有哪种RDBMS:
select ID, value
from YourTable
where id =
( select min(id)
from YourTable
where id >= 7
)
Try this for MS-SQL: 试试这个MS-SQL:
SELECT TOP 1
id, value
FROM your_table
WHERE id >= 7
ORDER BY id
or for MySql 或者对于MySql
SELECT id, value
FROM your_table
WHERE id >= 7
ORDER BY id
LIMIT 0,1
I would simply do it like this: 我会这样做:
select top 1 * from myTable where id >=7
order by id
implementation of the top 1
part is T-SQL (MSSQL/Sybase), other implementations vary but it is always possible (mysql/postgre LIMIT 1
, oracle rownum = 1
) top 1
部分的实现是T-SQL(MSSQL / Sybase),其他实现各不相同但总是可行的(mysql / postgre LIMIT 1
,oracle rownum = 1
)
select top 1 * from Persons where Id >= @Id order by Id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.