我知道这个问题在 StackOverFlow 中问了好几次。我试过其中的几个,但我运气不好。
我有一个 MySQL 表,其中有一个字段 (orders_id
) 可能会随机出现在表中(不按顺序),我需要找出表中缺少哪些 ID。
orders_id product_name qty 1007 Wireless Mouse 1 1000 Laptop 1 1004 Wireless Mouse 3 1020 PC 3 1003 Wireless Mouse 4 1025 IPAD 4 1026 iphone 1
Expected Answer:
Assume orders_id
start from 1000.
orders_id 1000 1001 1002 1005 1006 1008 ......
i have already created above table at "SqlFiddle" , you guys can use it.
**the SQL i have tried: **
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。
最佳答案
这是另一种解决方案:
CREATE TABLE TEMP
(n int);
INSERT INTO Temp VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
SET @maxid = (SELECT MAX(orders_id) FROM orders);
SELECT s.id
FROM
(
SELECT id
FROM
(
SELECT t4.n * 1000 + t3.n * 100 + t2.n * 10 + t1.n + 1 AS id
FROM TEMP AS t1
CROSS JOIN TEMP AS t2
CROSS JOIN TEMP AS t3
CROSS JOIN TEMP AS t4
) t
WHERE id BETWEEN 1000 AND @maxid
) s
LEFT JOIN orders t ON s.id = t.`orders_id`
WHERE t.`orders_id` IS NULL;
这应该为您提供 orders_id
:
ID
1001
1002
1005
1006
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1021
1022
1023
1024
SQL Fiddle Demo
请注意:我创建了一个包含 0 到 9 值的 TEMP
表,以便用于生成包含 1 到 10000 值的 anchor 表而不是while 循环,你在你发布的查询中。您可以根据表中的值控制此表中的值。如果您的值超过 10000 CROSS JOIN
,则再对 TEMP
表进行一次。
更新:如果 orders_id
的数据类型为 varchar
,只需将其转换为 INTEGER
,如下所示:
SELECT s.id
FROM
(
SELECT id
FROM
(
SELECT t4.n * 1000 + t3.n * 100 + t2.n * 10 + t1.n + 1 AS id
FROM TEMP AS t1
CROSS JOIN TEMP AS t2
CROSS JOIN TEMP AS t3
CROSS JOIN TEMP AS t4
) t WHERE id between 1000 AND @maxid
) s
LEFT JOIN
(
SELECT CONVERT(orders_id, UNSIGNED INTEGER) AS orders_id
FROM orders
) t ON s.id = t.`orders_id`
WHERE t.`orders_id` IS NULL;
Updated SQL Fiddle Demo
关于MySQL:找出丢失的订单 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13327743/