SQL - 查找最低的未使用数字

时间:2016-10-02 13:03:41

标签: mysql sql

我在2个不同的表中有一个'数字'列。这不是身份证。

我创建了一个像这样的联盟:

SELECT number FROM table1 UNION SELECT number FROM table ORDER BY number ASC

这导致以下结果:

number
=====
1
2
3
5
6
8

如何找到最低的未使用数字?在这种情况下,它将是4.一旦使用4,它将是7等等

3 个答案:

答案 0 :(得分:2)

这是一种方式:

select min(number + 1)
from t
where not exists (select 1 from t t2 where t2.number = t.number + 1);

有两个不同的表,我会将其称为:

select min(x)
from ((select min(number + 1) as x
       from t1 t
       where not exists (select 1 from t1 tt1 where tt1.number = t.number + 1)
             not exists (select 1 from t2 tt2 where tt2.number = t.number + 1)
      ) union all
      (select min(number + 1) as x
       from t2 t
       where not exists (select 1 from t1 tt1 where tt1.number = t.number + 1)
             not exists (select 1 from t2 tt2 where tt2.number = t.number + 1)
      )
     ) t;

这看起来更复杂,但它可以在每个表中使用(number)上的索引(如果存在这样的索引)。

答案 1 :(得分:1)

假设您的号码从1开始始终低于查询将提供未使用的号码

select min(rank) as Num from 
(select num,@curRank1 := @curRank1 + 1 AS rank from (SELECT num1 as num FROM t1 
UNION
SELECT num2 as num FROM t2) a1, (SELECT @curRank1 := 0) r ORDER BY num ASC) tab where num != rank;`

答案 2 :(得分:0)

假设您的变量number是INTEGER。

首先,我将在一个范围内创建一系列数字(下面介绍的过程是从此解决方案中提取的:get the first N positive integers

CREATE TABLE list_of_numbers (number INT NOT NULL PRIMARY KEY AUTO_INCREMENT)
CREATE PROCEDURE create_sequence_of_numbers(max_number INT)
BEGIN
        DECLARE _min_number INT;
        SET _min_number = 1;
        WHILE _min_number <= max_number DO
                INSERT INTO list_of_numbers SELECT  _min_number;
                SET _min_number = _min_number + 1;
        END WHILE;
END
$$

有了这个序列,我们可以创建以下查询:

select min(number) from list_of_numbers where number not in (SELECT your_number FROM table1 UNION SELECT your_number FROM table)