简体   繁体   中英

How to get next SQL row when the PRIMARY KEY values are not continuous?

INFO :
* I have a table with an INT PRIMARY KEY column called "s_id".
* The values for "s_id" are discontinuous, ie [3,5,7,8,9,11,12,14). So, [1,2,4,6,10,13] don't exist.

QUESTION :
Given prior knowledge of "s_id" value '5', what is the simplest SELECT statement for pulling "s_id" value '7'?

My latest attempt is hacky and arbitrary - the aim here being that if any rows exist I'd just pick the very first one and jump out:
SELECT s_id FROM s WHERE s_id > 5 AND s_id < (5+10)

EDIT: Sorry, I forgot to mention the limitation of SQLITE3, which does not offer 'TOP'. Nick and Marc's suggestion of using "TOP 1" steered me in the direction of learning about that limitation 1st hand, and then toward "LIMIT 1", which ended up working great. I figured SQL was SQL, I should have known better though:
SELECT s_id FROM s WHERE s_id > 5 LIMIT 1

How about:

SELECT TOP 1 s_id
FROM dbo.YourTable
WHERE s_id > 5
ORDER BY s_id 

That selects the first s_id value that's larger than 5 - in your case 7.

select top 1 s_id from s where s_id > 5 order by s_id

SELECT s_id FROM s WHERE s_id > 5 ORDER BY s_id LIMIT 1; in MySQL terms

用英语,您想要的最小s_id大于5。您可以在SQL中几乎以这种方式编写它。

select min(s_id) from yourtable where (s_id > 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM