找到缺少序列间隙的mysql

时间:2012-09-21 13:38:13

标签: mysql sequence

  

可能重复:
  how to find missing value in sequence within groups in SQL?

我的列值为

MAC00006300
MAC00006301
MAC00006302
MAC00006305
.....
LED00006002
...........
LED00006008
ALD18965
ALD18967
ALD18968
.......
ALD19000

我需要在值之间缺少

MAC00006303,MAC00006304 
LET00006003 ..... LET00006007
ALD18969,ALD18970.....ALD18989

SELECT NAME, VALUE + 1
FROM testmissingexampledata  mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    testmissingexampledata mi 
        WHERE   mi.VALUE = mo.VALUE + 1
        )
ORDER BY
        VALUE;

当我执行上述查询时,我只能检索下一条缺失的记录。任何人都可以向我建议如何检索所有丢失的记录吗?

1 个答案:

答案 0 :(得分:1)

如果没有所有可能的数值列表,则不能将缺少的行返回到LEFT JOIN

这个查询(感觉它可能更好/更强/更快,但它有效)会找到你的空白:

set @last_prefix = null;
set @last_value = null;
select result from (
    select @last_prefix, @last_value, name,
      @prefix := substring(name,1,3) as prefix,
      @value := substring(name,4) as value,
      case when @prefix = @last_prefix and @value != @last_value +1
        then concat ("gap from ", @prefix, ": ", @last_value+1, " to ", @value-1)
        else "ok" end as result,
      @last_prefix := @prefix, @last_value := @value
      from t20120921
) foo
where result != "ok";