简体   繁体   English

MySQL-检查VARCHAR列的增量是否缺少值

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

I'm trying to find out if my values inserted are auto-incrementing correctly or if for any reason one has failed to be inserted, deleted or gone "missing". 我试图找出插入的值是否正确地自动递增,或者由于某种原因插入,删除或“丢失”失败。 I've tried several answers from Stackoverflow but they were mainly pointing out autoincrementable int values so they did not help since mine is a VARCHAR value that follows the following sequence: 我已经尝试了Stackoverflow的几个答案,但是它们主要是指出可自动递增的int值,因此它们无济于事,因为mine是遵循以下顺序的VARCHAR值:

AA000001
AA000002
...
AA000100
...
AA213978

and so on... 等等...

Thanks for your time. 谢谢你的时间。

You can declare SQL Vars in Query and calculate the difference in each iteration, as shown in the example below: 您可以在Query中声明SQL Vars,并在每次迭代中计算差异,如下例所示:

Schema 架构图

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

Query 询问

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; 

This is the inside query (not the final result set of the above) 这是内部查询(不是上面的最终结果集)

+----------+--------+------+------------+-------+
| 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 |
+----------+--------+------+------------+-------+

Actual Results of Above Query: 以上查询的实际结果:

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

Here's the SQL Fiddle . 这是SQL Fiddle

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM