這是非常快的,我因爲我們避免了連接,並且只能遍歷數據一次。唯一的瓶頸是我們使用2個臨時表,並且需要使用用戶定義的值。
沒有SET語句
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:[email protected],@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 @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:[email protected],@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
你嘗試在你的數據集查詢。任何結果? –