我正在寻找一种解决方案,以便在表格中找到未使用的号码。到目前为止我遇到的大多数解决方案是创建一个包含所有数字的临时表,并使用左连接来查找未使用的数字。就我而言,我没有机会创建一个临时表。
带前导零的数字范围:0001-1999
。这些号码是拨号盘号码,长度必须是4位数。
列表表:
+----+--------+------------+
| id | title | pad_number |
+----+--------+------------+
| 1 | Foo | 0001 |
| 2 | bar | 0005 |
| 3 | Baz | 1999 |
| 10 | FooBar | 0002 |
+----+--------+------------+
预期结果:
0003
有没有办法检索号码?
答案 0 :(得分:1)
使用not exists
。
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 :(得分:1)
我会这样做:
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);