如何在mysql中找到无间隙的序列号?

时间:2013-10-07 10:35:55

标签: mysql

考虑一个带有serialnumber列的表productSerialnumber。此列采用产品的单个序列号。

产品A的序列号为101到109,然后是111到119和139到150.序列号110和120-138例如不可用

我想要一个可以返回连续序列号集的查询或其他东西。 例如,结果将是

from       to 
=======    ====
101        109
111        119
139        150

需要考虑的是,该表拥有超过一百万行的大量数据。

任何帮助都会非常适合

2 个答案:

答案 0 :(得分:2)

玩的更多: -

SELECT MIN(aFirstSerial), MAX(aLastSerial)
FROM
(
    SELECT @FirstSerial:=IF(productSerialnumber = @LastSerial + 1, IF(@FirstSerial = 0, productSerialnumber, @FirstSerial), productSerialnumber) AS aFirstSerial, 
        @RangeNum:=IF(productSerialnumber = @LastSerial + 1, @RangeNum, @RangeNum + 1) AS aRangeNum, 
        @LastSerial := productSerialnumber AS aLastSerial
    FROM
    (
        SELECT productSerialnumber
        FROM Product
        ORDER BY productSerialnumber
    ) Sub1
    CROSS JOIN (SELECT @PrevSerial:=0, @RangeNum:=0, @FirstSerial:=0, @LastSerial:=0) Sub2
) Sub3
GROUP BY aRangeNum

这里的SQL小提琴: -

http://sqlfiddle.com/#!2/5cbc2/12

答案 1 :(得分:0)

在我看来,这是非常快的,因为我们避免了连接并且只迭代数据一次。唯一的瓶颈是我们使用2个临时表,需要使用用户定义的值。

没有set statement

select START_INTERVAL+0, END_INTERVAL+0
from
(
  select 
  if(@start = NULL or @start > PRODUCTSERIALNUMBER, @start='', '') as SET_START,
  if (@start = '', @start:= @previous, @start) as START_INTERVAL,
  if(PRODUCTSERIALNUMBER - @previous > 1, concat(@end:=@previous,@start:=''), @end:='') as END_INTERVAL,
  @previous:= PRODUCTSERIALNUMBER as PRODUCTSERIALNUMBER
  from 
  (
    select min(PRODUCTSERIALNUMBER)-2 as PRODUCTSERIALNUMBER from Product
    UNION
    (select PRODUCTSERIALNUMBER as PRODUCTSERIALNUMBER from Product ORDER BY productSerialnumber)
    UNION
    select max(PRODUCTSERIALNUMBER)+2 as PRODUCTSERIALNUMBER from Product    
  ) as TEMP
)
as RESULTS where 
not START_INTERVAL is null AND
not END_INTERVAL is null AND
not END_INTERVAL = '' AND
not START_INTERVAL - END_INTERVAL > 0;

使用Set语句

set @start='';

select select START_INTERVAL+0, END_INTERVAL+0
from
(
  select 
  if (@start = '', @start:= @previous, @start) as START_INTERVAL,
  if(PRODUCTSERIALNUMBER - @previous > 1, concat(@end:=@previous,@start:=''), @end:='') as END_INTERVAL,
  @previous:= PRODUCTSERIALNUMBER as PRODUCTSERIALNUMBER
  from 
  (
    select min(PRODUCTSERIALNUMBER)-2 as PRODUCTSERIALNUMBER from Product
    UNION
    (select PRODUCTSERIALNUMBER as PRODUCTSERIALNUMBER from Product ORDER BY productSerialnumber)
    UNION
    select max(PRODUCTSERIALNUMBER)+2 as PRODUCTSERIALNUMBER from Product    
  ) as TEMP
)
as RESULTS where 
not RESULTS.START_INTERVAL is null AND
not RESULTS.END_INTERVAL is null AND
not RESULTS.END_INTERVAL = '' AND
not RESULTS.START_INTERVAL - RESULTS.END_INTERVAL > 0;

SQLFiddle:http://sqlfiddle.com/#!2/a622a/60