用sql语句获取连续整数id中,缺失的最小id和最大id
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
例如數(shù)據(jù)庫(kù)表 table 結(jié)構(gòu)和數(shù)據(jù)如下,要求使用sql語句查詢出連續(xù)整數(shù)id中,缺失的最小和最大id。
從數(shù)據(jù)來看,最終結(jié)果應(yīng)該為:最小 4,最大 14。
| id |
| 1 |
| 2 |
| 3 |
| 5 |
| 7 |
| 8 |
| 10 |
| 15 |
| 16 |
一、獲取缺失的最小id
可以在現(xiàn)有的所有id加1,select id+1 from table; 得到
| 2 |
| 3 |
| 4 |
| 6 |
| 8 |
| 9 |
| 11 |
| 16 |
| 17 |
由于id序列是以整數(shù)+1的形式遞增,那么這個(gè)序列中必然存在最小的缺失id,
去掉表中存在的id,并得到最小值就是我們需要的結(jié)果。
select MIN(id+1) from table t1
where not exists(select * from table t2 where t2.id = t1.id + 1);
二、獲取缺失的最大id
與上面的操作相反,查詢id減1的數(shù)字序列?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
轉(zhuǎn)載于:https://my.oschina.net/u/992937/blog/1648363
總結(jié)
以上是生活随笔為你收集整理的用sql语句获取连续整数id中,缺失的最小id和最大id的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能,不止于技术的革命--WOT20
- 下一篇: Java10来了,来看看它一同发布的全新