我被问到以下内容:我有一个表(叫它tbl),它有一列int类型(叫它num),里面有序号:

num
---
 1
 2
 4
 5
 6
 8
 9
 11

现在,您需要编写一个查询,该查询返回第一个缺失的数字(在此示例中,答案将为3)。

这是我的答案(有效):
select top 1 (num + 1)
from tbl
where (num + 1) not in (select num from tbl)

写完这些后,我被问到tbl是否包含1000万条记录-您将如何提高性能(因为显然myinner查询会引起全表扫描)。

我的想法是关于num字段中的索引,并且不存在。但我很想听听其他选择。

最佳答案

在SQL Server 2012+中,我将只使用lead():

select num
from (select num, lead(num) over (order by num) as next_num
      from tbl
     ) t
where next_num <> num + 1;

但是,我怀疑如果在tbl(num)上具有索引,则您的版本将具有最佳性能。 not exists版本值得测试:
select top 1 (num + 1)
from tbl t
where not exists (select 1 from tbl t2 where t2.num = t.num + 1);

唯一的问题是获得第一个数字。您不能保证该表是按顺序读取的。因此,这将返回一个数字。使用num上的索引(或者更好的是聚集索引),以下操作应该很快并保证返回第一个数字:
select top 1 (num + 1)
from tbl t
where not exists (select 1 from tbl t2 where t2.num = t.num + 1)
order by num;

10-07 19:47
查看更多