gpt4 book ai didi

MySQL 在具有多个 ID 的列中查找空白

转载 作者:搜寻专家 更新时间:2023-10-30 23:39:23 25 4
gpt4 key购买 nike

我想找出下表中的空白:

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

我知道,“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

最佳答案

你可以使用 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);

关于MySQL 在具有多个 ID 的列中查找空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36956178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com