SQL查找下一个可用的字符串键

时间:2014-04-11 10:28:06

标签: mysql key

我需要在具有字符串键的表上找到下一个可用ID。 I have followed an example here。我的例子如下:

菜肴表(第一列)

Table_id
DSH0000000003
DSH0000000004
DSH0000000005
DSH0000000007

SQL:

SELECT CONCAT('DSH',LPAD(MIN(SUBSTRING(t1.dish_id FROM 4) + 1), 10, '0')) AS nextID
FROM dishes t1
WHERE NOT EXISTS (SELECT t2.dish_id 
          FROM dishes t2
          WHERE SUBSTRING(t2.dish_id FROM 4) = SUBSTRING(t1.dish_id FROM 4) + 1)

输出:

DSH0000000006

如果我删除#5然后它返回#5但它不返回" DSH0000000001"。

2 个答案:

答案 0 :(得分:0)

您应该添加一个初始值测试。使用您当前的方法,您只能获得大于表中存在的最小值的值。

您可以使用IF()来区分这两种可能性。

答案 1 :(得分:0)

您可以使用变量来构建连续的ID,然后比较第一个不匹配的ID的位置:

SELECT
  CONCAT('DSH', LPAD(seq, 10, '0')) AS k
FROM
  (SELECT
    @seq:=@seq+1 AS seq,
    num
  FROM
    (SELECT
       CAST(SUBSTR(table_id, 4) AS UNSIGNED) AS num
     FROM
       t
     UNION ALL
     SELECT
        MAX(CAST(SUBSTR(table_id, 4) AS UNSIGNED))+2 AS num
     FROM 
       t
     ORDER BY
       num) AS ids
   CROSS JOIN 
      (SELECT @seq:=0) AS init 
  ) AS pairs
WHERE
  seq!=num
LIMIT 1

小提琴可用here