我认为这非常快,因为我们避免了连接并且只遍历数据一次。唯一的瓶颈是我们使用了 2 个临时表,并且需要使用用户定义的值。
没有设置语句
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