sql_找出等差数列中的缺少项(非连续)

来源:互联网 发布:交换机端口设248 编辑:程序博客网 时间:2024/06/06 00:19

首先,有一张表的某一个字段是递增字段,现在需要找到递增字段中的缺少项。

举一个例子,1,2,3,4,6,7,8……这个数列中的缺少项就是5,我们的任务就是找出5。

以下操作基于mysql数据库:

1.创建一张表

create table t_increment(id int);

2.插入模拟数据

insert into t_increment(id) values(1);insert into t_increment(id) values(null);insert into t_increment(id) values(2);insert into t_increment(id) values(4);insert into t_increment(id) values(6);insert into t_increment(id) values(7);

3.查出该字段中缺少的数据

3.1:该表自己对自己做左连接查询

在本例中,等差为1,所以将id字段加1。

select a.id+1 c,b.id d from t_increment a left join t_increment b on a.id+1 =b.id;
3.2:将3.1中查出的数据作为一张表,去除c字段为null的和排序后的最后一个,得到的就是最终的空缺字段

select * from (select a.id+1 c,b.id d from t_increment a left join t_increment b on a.id+1 =b.id) e where e.c is not null order by e.c;
3.3最终结果(不包含最后一行)

+------+------+| c    | d    |+------+------+|    2 |    2 ||    3 | NULL ||    5 | NULL ||    7 |    7 ||    8 | NULL |+------+------+