如何在表格中找到未占用的ID号码?

时间:2014-11-26 07:59:30

标签: sql oracle11g

在我的表中,我想查看某个范围内未占用的ID号列表。

例如,我的表中有10条记录带有id'" 2,3,4,5,10,12,16,18,21,22"并说我希望在1到25之间看到可用的。所以我想看一个像这样的列表:

1,6,7,89,11,13,14,15,17,19,20,23,24,25

我该如何编写我的SQL查询?

4 个答案:

答案 0 :(得分:2)

选择1到25之间的数字,仅显示表格中没有的数字

select n from
( select rownum n from dual connect by level <= 25)
where n not in (select id from table);

答案 1 :(得分:0)

让我们说一个带有三个数字的#numbers表 -

CREATE TABLE #numbers (num INT)

INSERT INTO #numbers (num)
SELECT 1
UNION
SELECT 3
UNION
SELECT 6

现在,您可以使用CTE从1-25递归生成数字,并取消选择WHERE子句中#numbers表中的数字 -

;WITH n(n) AS
(
    SELECT 1
    UNION ALL
    SELECT n+1 FROM n WHERE n < 25
)
SELECT n FROM n 
WHERE n NOT IN (select num from #numbers)
ORDER BY n
OPTION (MAXRECURSION 25);

答案 2 :(得分:0)

您可以尝试使用“NOT IN”子句:

select
    u1.user_id + 1 as start
from users as u1
  left outer join users as u2 on u1.user_id + 1 = u2.id
where
    u2.id is null

另见SQL query to find Missing sequence numbers

答案 3 :(得分:0)

您需要LISTAGG才能获得单行输出。

SQL> WITH DATA1 AS(
  2  SELECT LEVEL rn FROM dual CONNECT BY LEVEL <=25
  3  ),
  4  data2 AS(
  5  SELECT 2 num FROM dual UNION ALL
  6  SELECT 3 FROM dual UNION ALL
  7  SELECT 4 from dual union all
  8  SELECT 5 FROM dual UNION ALL
  9  SELECT 10 FROM dual UNION ALL
 10  SELECT 12 from dual union all
 11  SELECT 16 from dual union all
 12  SELECT 18 FROM dual UNION ALL
 13  SELECT 21 FROM dual UNION ALL
 14  SELECT 22 FROM dual)
 15  SELECT listagg(rn, ',')
 16  WITHIN GROUP (ORDER BY rn) num_list FROM data1
 17  WHERE rn NOT IN(SELECT num FROM data2)
 18  /

NUM_LIST
----------------------------------------------------
1,6,7,8,9,11,13,14,15,17,19,20,23,24,25

SQL>