MySQL查询跳过001号码

时间:2017-11-07 14:51:32

标签: php mysql sql

这是我之前回答的问题的后续问题 - Determine the next number in database query with while loop in php

如果我有产品标签

products TABLE
==============
ABC001
ABC002
ABC003
ABC005
==============

并使用此

SELECT SUBSTR(t1.id, 4) + 1 as POSSIBLE_MIN_ID
FROM products t1
WHERE NOT EXISTS (
    SELECT * 
    FROM products t2
    WHERE SUBSTR(id, 1, 3)='ABC' AND SUBSTR(t2.id, 4) = SUBSTR(t1.id, 4) + 1
) LIMIT 1

我得到4的结果。但是,如果我有表格

products TABLE
==============
ABC005
ABC006
ABC007
ABC008
==============

它给了我9的结果。如果我在表格中没有,则会给我2而不是1的结果。如果我添加ABC001,它就可以了。为什么这样,有没有办法解决它,所以它也拿起1?如果没有ABC001,我怎样才能让它正常工作?

感谢!

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要第一个未使用的' ABCnnn'。所以如果' ABC001'仍然可以得到这个,否则尝试' ABC002'等等。

一种方法是创建所有代码' ABC001'到#99; ABC999'然后删除表中已有的那些。从这些中取出至少一个。

您可以使用任何方法生成数字,甚至可以使用包含所有允许代码的表格。在这里,我使用二进制数学来创建数字:

select min(code) as new_code
from
(
  select concat('ABC', lpad(num,3,'0')) as code
  from
  (
    select a.x + b.x * 2 + c.x * 4 + d.x * 8 + e.x * 16 + f.x * 32 +
           g.x * 64 + h.x * 128 + i.x * 256 + j.x * 512 as num
    from (select 0 as x union all select 1) a
    cross join (select 0 as x union all select 1) b
    cross join (select 0 as x union all select 1) c
    cross join (select 0 as x union all select 1) d
    cross join (select 0 as x union all select 1) e
    cross join (select 0 as x union all select 1) f
    cross join (select 0 as x union all select 1) g
    cross join (select 0 as x union all select 1) h
    cross join (select 0 as x union all select 1) i
    cross join (select 0 as x union all select 1) j
  ) numbers
  where num between 1 and 999
) codes
where code not in (select id from products);

除此之外,我还修复了错误的数据库设计。商店' ABC'与数字分开。如果它总是' ABC',则根本不存储该字符串。

答案 1 :(得分:0)

如果它只是您使用的最大使用ID加1:

select concat('ABC', lpad(coalesce(max(substr(id, 4, 3)), 0) + 1, 3, '0')) as new_id
from products;
相关问题