用sql语句获取连续整数id中,缺失的最小id和最大id
2019獨角獸企業重金招聘Python工程師標準>>>
例如數據庫表 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
轉載于:https://my.oschina.net/u/992937/blog/1648363
總結
以上是生活随笔為你收集整理的用sql语句获取连续整数id中,缺失的最小id和最大id的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能,不止于技术的革命--WOT20
- 下一篇: Java10来了,来看看它一同发布的全新