MySQL:找出丢失的订单ID

时间:2012-11-11 01:15:28

标签: mysql sql database

我在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

预期答案:

假设orders_id 1000 开始。

  orders_id     
       1000 
       1001
       1002     
       1005      
       1006    
       1008      
      ......  


我已经在“SqlFiddle”创建了上表,你们可以使用它。

See table: 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。

1 个答案:

答案 0 :(得分:4)

这是另一种解决方案:

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 s:

ID
1001
1002
1005
1006
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1021
1022
1023
1024

SQL Fiddle Demo

请注意:我创建了一个TEMP表,其值为0到9,以便用于生成包含1到10000之间的值的锚表,而不是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