【问题标题】:Mysql - Check if VARCHAR column has a missing value on its incrementationMysql - 检查 VARCHAR 列的增量是否有缺失值
【发布时间】:2016-09-20 07:15:52
【问题描述】:

我正在尝试确定我插入的值是否正确地自动递增,或者是否由于某种原因未能插入、删除或“丢失”。我已经尝试了 Stackoverflow 的几个答案,但它们主要是指出可自动递增的 int 值,因此它们没有帮助,因为我的 VARCHAR 值遵循以下顺序:

AA000001
AA000002
...
AA000100
...
AA213978

等等……

感谢您的宝贵时间。

【问题讨论】:

  • 是固定模式AAxxxxxx?
  • 甚至可能是etc000001 ...
  • 或者可以是“AAAxxxxx”吗?因为如果只有 2 个,您可以使用 substringleftright 来削减 varchar
  • @Drew,不,添加等是为了解释它超出了 AA213978,抱歉造成混淆,让我修复它。
  • 我在幽默方面的糟糕尝试

标签: mysql sql auto-increment varchar


【解决方案1】:

您可以在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

【讨论】:

  • table 是保留字,所以需要反引号
  • 那里,修正了一些错别字,不知道是不是你想要的结果
  • 忘了说插入的值是递增的但不是ID本身,也可以不连续按照ID插入
  • @this.user3272243 它将显示上一行的 id 和当前 id 之间的差异。我们可以检查差异列,如果大于1,我们可以说跳过了一个id。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多