Mysql - 检查 VARCHAR 列在递增时是否有缺失值

Mysql - Check if VARCHAR column has a missing value on its incrementation

我试图查明我插入的值是否正确地自动递增,或者是否由于任何原因未能插入、删除或消失 "missing"。我已经尝试了 Whosebug 的几个答案,但它们主要指出了可自动递增的 int 值,所以它们没有帮助,因为我的是一个遵循以下顺序的 VARCHAR 值:

AA000001
AA000002
...
AA000100
...
AA213978

等等...

感谢您的宝贵时间。

可以在Query中声明SQL个Vars,计算每次迭代的差值,如下例所示:

架构

create table MyTable
(   ai int auto_increment primary key,
    id varchar(100) not null
);
insert MyTable (id) values
('AA000001'),
('AA000002'),
('AA000005'),
('AA000008'),
('AA000009'),
('AA000010');

查询

select id 
FROM 
( 
    select 
      t.id, 
      SUBSTRING(t.id,3) as s, 
      CAST(SUBSTRING(t.id,3) AS UNSIGNED) - @lastId as diff, 
      if( @lastId = 0, 0, CAST(SUBSTRING(t.id,3) AS UNSIGNED) - @lastId) as Difference, 
      @lastId := CAST(SUBSTRING(t.id,3) AS UNSIGNED) as dummy 
     from 
      `MyTable` t, 
      ( select @lastId := 0) SQLVars 
     order by 
      t.id 
) d 
WHERE diff>1; 

这是内部查询(不是上面的最终结果集)

+----------+--------+------+------------+-------+
| id       | s      | diff | Difference | dummy |
+----------+--------+------+------------+-------+
| AA000001 | 000001 |    1 |          0 |     1 |
| AA000002 | 000002 |    1 |          1 |     2 |
| AA000005 | 000005 |    3 |          3 |     5 |
| AA000008 | 000008 |    3 |          3 |     8 |
| AA000009 | 000009 |    1 |          1 |     9 |
| AA000010 | 000010 |    1 |          1 |    10 |
+----------+--------+------+------------+-------+

上述查询的实际结果:

+----------+
| id       |
+----------+
| AA000005 |
| AA000008 |
+----------+

这是 SQL Fiddle

为了简单地测试是否有 个缺失值,

select count(*) <> max(right(col, 6))-min(right(col, 6))+1 || count(*) <> count(distinct col)