2016-09-20 45 views
0

我試圖找出插入的值是否自動遞增正確,或者如果由於任何原因導致一個插入,刪除或失蹤「失蹤」 。我試着從幾個#1的答案,但他們主要是指出autoincrementable INT值,所以他們並沒有幫助,因爲我的是順序如下一個VARCHAR值:Mysql - 檢查VARCHAR列的增量是否有缺失

AA000001 
AA000002 
... 
AA000100 
... 
AA213978 

等等...

感謝您的時間。

+1

是固定圖案AAxxxxxx? –

+0

甚至可能是'etc000001' ... – Drew

+0

還是可以'AAAxxxxx'?因爲如果只有2你可以使用'substring'或'left'或'right'來切割'varchar' – Nebi

回答

3

可以在查詢聲明SQL瓦爾和計算在每個迭代的差,如下面的例子:

架構

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

+0

表是一個保留字,所以它需要備份 – Drew

+0

完成,謝謝指出。 –

+0

在那裏,修正了一些錯別字,不確定這是你想要的結果 – Drew

0

爲了簡單地測試是否有缺失值,

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