3 回答

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您的第一個(gè)值id = 1,則所有答案都可以正常工作,否則將不會(huì)檢測到該差距。例如,如果您的表ID值為3、4、5,則查詢將返回6。
我做了這樣的事情
SELECT MIN(ID+1) FROM (
SELECT 0 AS ID UNION ALL
SELECT
MIN(ID + 1)
FROM
TableX) AS T1
WHERE
ID+1 NOT IN (SELECT ID FROM TableX)

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
我想到的第一件事。不確定完全采用這種方式是否是個(gè)好主意,但應(yīng)該可以。假設(shè)表為t,列為c:
SELECT t1.c+1 AS gap FROM t as t1 LEFT OUTER JOIN t as t2 ON (t1.c+1=t2.c) WHERE t2.c IS NULL ORDER BY gap ASC LIMIT 1
編輯:這可能是一個(gè)更快的滴答聲(并且更短?。?/p>
SELECT min(t1.c)+1 AS gap FROM t as t1 LEFT OUTER JOIN t as t2 ON (t1.c+1=t2.c) WHERE t2.c IS NULL
添加回答
舉報(bào)