如何在SQL中找到范围的差距

时间:2013-07-22 07:55:01

标签: sql sqlite postgresql gaps-and-islands

This question解释了如何在表中找到第一个“未使用”的数字,但是如何找到相同的数字以便我可以定义额外的约束。如何更改查询,以便在大于100之后获得第一个未使用的数字

e.g。如果我的桌子上有23,56,100,101,103,我应该得到102.

5 个答案:

答案 0 :(得分:5)

在mysql和postgresql中

SELECT  id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        ) and mo.id> 100
ORDER BY
        id
LIMIT 1

fiddle for mysqlfiddle for postgresql

ms sql

SELECT  TOP 1
        id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        )
          and mo.id > 100
ORDER BY
        id

fiddle

答案 1 :(得分:3)

在Oracle Sql中,您可以尝试:

SELECT id
FROM
     (SELECT ID, lead(ID) OVER(ORDER BY ID) next_val FROM my_table t
     )
WHERE id +1 <> next_val
 AND id      >100;

答案 2 :(得分:1)

希望这会对你有所帮助

SELECT MIN (id) + 1
  FROM myTable T1
 WHERE id >= 100
   AND NOT EXISTS (SELECT *
                     FROM myTable T2
                    WHERE T1.id + 1 = T2.id)

答案 3 :(得分:0)

使用generate_series()获得乐趣&amp;利润:

CREATE table islands (num INTEGER NOT NULL PRIMARY KEY);

INSERT INTO islands (num ) VALUES
(23), (56), (100), (101), (103) ;

WITH total AS (
        SELECT generate_series(mima.bot, mima.top) AS num
        FROM ( SELECT MIN(num) AS bot , MAX(num) AS top FROM islands) mima
        )
SELECT num
FROM total tt
WHERE num >=100
AND NOT EXISTS (
        SELECT *
        FROM islands ii
        WHERE ii.num = tt.num
        )
        ;

答案 4 :(得分:0)

使用它:

SELECT TOP 1 a1.id + 1 FROM test a1 left JOIN test a2 
ON a1.id = a2.id - 1 
WHERE a2.id IS NULL AND a1.id > 100