【发布时间】:2012-10-30 22:24:57
【问题描述】:
我知道这个问题在 StackOverFlow 中被问过多次。我已经尝试了其中的几个,但我不走运。
我有一个 MySQL 表,其中有一个字段 (orders_id),它可能会随机出现在表中(非顺序),我需要找出表中缺少哪些 id。
预期答案:
假设orders_id从1000开始。
我已经在“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:
SQL: find missing IDs in a table
我也尝试过 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。
【问题讨论】:
-
“我试过的SQL”以什么方式失败?假设您的
order_id也是一个整数,这看起来是一个合理的解决方案。如果这不起作用,请描述发生了什么。 -
Order_id 是原始表 nut 中的“varchar”,我可以转换为 INT,问题是在“declare @id int”处出现以下错误。
-
[Err] 1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在 'declare @id int declare @maxid int set @id = 1 select @maxid = max(`zencart' at line 1 附近使用正确的语法