1

我想在下表中找到差距:

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 );

预期的结果是这样的:

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

或者

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

我知道,列“值”的值在 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

4

1 回答 1

2

你可以这样做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);
于 2016-04-30T14:57:26.100 回答