例如数据库表 table 结构和数据如下,要求使用sql语句查询出连续整数id中,缺失的最小和最大id。
从数据来看,最终结果应该为:最小 4,最大 14。
id |
1 |
2 |
3 |
5 |
7 |
8 |
10 |
15 |
16 |
一、获取缺失的最小id
可以在现有的所有id加1,select id+1 from table; 得到
2 |
3 |
4 |
6 |
8 |
9 |
11 |
16 |
17 |
由于id序列是以整数+1的形式递增,那么这个序列中必然存在最小的缺失id,
去掉表中存在的id,并得到最小值就是我们需要的结果。
select MIN(id+1) from table t1
where not exists(select * from table t2 where t2.id = t1.id + 1);
二、获取缺失的最大id
与上面的操作相反,查询id减1的数字序列 select id+1 from table;
0 |
1 |
2 |
4 |
6 |
7 |
9 |
14 |
15 |
去掉表中已有id,注意范围不能超过表中最大id
select MAX(id-1) from table t1
where not exists(select * from table t2 where t2.id = t1.id - 1)
and id < (select MAX(id) from table)
得到14