0
点赞
收藏
分享

微信扫一扫

Mysql求最小正整缺失值

zibianqu 2022-01-28 阅读 26


Mysql求最小正整缺失值

1.需求

给出一串数字,求出这串数字中的最小正整缺失值

2.示例

  • 查看表数据
mysql> select * from x;
+------+
| a |
+------+
| 3 |
| 4 |
| 5 |
| 6 |
+------+
4 rows in set (0.00 sec)

对于上述的表数据,最小的缺失值应该是7.【这个最小缺失值从表中已存在的数字开始】

3.代码

mysql> select
-> min(a) + 1 as missing
-> from x as a
-> where not exists
-> (select * from x as b
-> where a.a+1 = b.a);
+---------+
| missing |
+---------+
| 7 |
+---------+
1 row in set (0.00 sec)
  • 如果是从正整数集角度考虑,那么最小缺失值就是1
    代码如下:
select 
case when not exists (select a from x where a = 1) then 1
else
(select
min(a) + 1 as missing
from x as a
where not exists
(select * from x as b
where a.a+1 = b.a)
)
end as missing;

+---------+
| missing |
+---------+
| 1 |
+---------+
1 row in set (0.00 sec)



举报

相关推荐

0 条评论