开发者

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, i.e. [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 j开发者_JS百科ump 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


In English, you want the smallest s_id that's greater than 5. You can write it almost just that way in SQL.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜