MySQL在具有多个ID的列中查找间隙

时间:2016-04-30 14:35:54

标签: mysql sql database gaps-in-data

我想在下表中找到空白:

create table sequence
(
   `Id` int,
   `Value` int not null,
   PRIMARY KEY (`Id`,`Value`)
);

insert into sequence
    ( `Id`, `Value` )
  values
    (10, 0 ),
    (10, 1 ),
    (10, 4 ),
    (10, 5 ),
    (10, 6 ),
    (10, 7 ),
    (11, 0 ),
    (11, 1 ),
    (11, 2 ),
    (11, 5 ),
    (11, 7 );

Expeced结果类似于:

10 | 2-3
11 | 3-4
11 | 6

10 | 2
10 | 3
11 | 3
11 | 4
11 | 6

我知道,colum'Value'的值在0到7之间。

是否可以使用MySQL进行此操作?

编辑1

根据答案,我来了:

SELECT Tbl1.Id, 
       startseqno, 
       Min(B.Value) - 1 AS END 
FROM   (SELECT Id, 
               Value + 1 AS StartSeqNo 
        FROM   SEQUENCE AS A 
        WHERE  NOT EXISTS (SELECT * 
                           FROM   SEQUENCE AS B 
                           WHERE  B.Id = A.id 
                                  AND B.Value = A.Value + 1) 
               AND Value < (SELECT Max(Value) 
                            FROM   SEQUENCE B 
                            WHERE  B.Id = A.Id)) AS Tbl1, 
       SEQUENCE AS B 
WHERE  B.Id = Tbl1.Id 
       AND B.Value > Tbl1.startseqno 

但现在我只是

10 | 2 | 3

拜托,有人知道,如何解决?

sqlfiddle

1 个答案:

答案 0 :(得分:1)

您可以使用not exists

执行此操作
select s.*
from sequence s
where not exists (select 1 from sequence s2 where s2.id = s.id and s2.value = s.value + 1) and
      exists (select 1 from sequence s2 where s2.id = s.id and s2.value > s.value);

exists条款非常重要,因此您不会报告每个id的最终值。

编辑:

这是一种更好的方法:

select s.value + 1 as startgap,
       (select min(s2.value) - 1 from sequence s2 where s2.id = s.id and s2.value > s.value) as endgap
from sequence s
where not exists (select 1 from sequence s2 where s2.id = s.id and s2.value = s.value + 1) and
      exists (select 1 from sequence s2 where s2.id = s.id and s2.value > s.value);