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