首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MySQL表中查找第一个未使用的号码

在MySQL表中查找第一个未使用的号码
EN

Stack Overflow用户
提问于 2018-03-15 08:49:01
回答 2查看 232关注 0票数 0

我正在寻找一个解决方案,以便在表格中找到一个未使用的数字。到目前为止,我遇到的大多数解决方案都是创建一个包含所有数字的临时表,并使用left join查找未使用的数字。在我的例子中,我没有机会创建临时表。

前导为零的数字范围:0001-1999。这些号码是拨号盘号码,长度必须为4位数字。

列表:

代码语言:javascript
复制
+----+--------+------------+
| id | title  | pad_number |
+----+--------+------------+
|  1 | Foo    |       0001 |
|  2 | bar    |       0005 |
|  3 | Baz    |       1999 |
| 10 | FooBar |       0002 |
+----+--------+------------+

预期结果:

代码语言:javascript
复制
0003

有没有办法找回号码?

EN

回答 2

Stack Overflow用户

发布于 2018-03-15 11:10:45

我会这样做:

代码语言:javascript
复制
select lpad(min(pad_number) + 1, 4, '0')
from t
where not exists (select 1 from t t2 where t2.pad_number = t.pad_number + 1);
票数 2
EN

Stack Overflow用户

发布于 2018-03-15 08:51:30

使用not exists

代码语言:javascript
复制
select lpad(cast(cast(pad_number as unsigned)+1 as char(4)),4,'0')
from tbl t
where not exists (select 1 from tbl t1 
                  where cast(t.pad_number as unsigned)=cast(t1.pad_number as unsigned)-1)
and cast(pad_number as unsigned) >=0 and cast(pad_number as unsigned) < 1999
order by 1
limit 1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49289885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档