我知道这个问题在 StackOverFlow 中被问了好几次。我已经尝试了其中的几个,但我不走运。
我有一个 MySQL 表,其中有一个字段(orders_id),它可能会随机出现在表中(不是按顺序),我需要找出表中缺少哪些 id。
orders_id product_name 数量
1007无线鼠标1
1000 笔记本电脑 1
1004无线鼠标3
1020 个人电脑 3
1003无线鼠标4
第1025章 4
1026 iphone 1
预期答案:
假设orders_id从1000开始。
订单编号
1000
1001
1002
1005
1006
1008
……
我已经在“SqlFiddle”创建了上表,你们可以使用它。
**我尝试过的 SQL:**
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(`orders_id`) from orders
create temporary table IDSeq
(
id int
)
while @id < @maxid
begin
insert into IDSeq values(@id)
set @id = @id + 1
end
select
s.id
from
idseq s
left join orders t on
s.id = t.`orders_id`
where t.`orders_id` is null
drop table IDSeq
我从以下答案中获取了上述 SQL:
我也尝试过 ANSI SQL:
SELECT a.orders_id+1 AS start, MIN(b.orders_id) - 1 AS end
FROM orders AS a, orders AS b
WHERE a.orders_id < b.orders_id
GROUP BY a.orders_id
HAVING start < MIN(b.orders_id)
任何人有任何想法?我怎样才能找到丢失的订单 ID。