Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find serial numbers without gap in mysql?

Tags:

mysql

Consider a table productSerialnumber with a column serialnumber. this column takes a single serial number of a Product.

Product A has a serial number from 101 to 109 and then 111 to 119 and 139 to 150. the serialnumber 110 and 120-138 for example are not availabel

I would like to have a query or something that can return continous serialnumber set. for example the result will be

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

to be considered is that table has a huge set of data more then a million rows.

Any help will be really appriciated

like image 415
Casado cMS Avatar asked Dec 05 '25 13:12

Casado cMS


1 Answers

Had more of a play:-

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 Fiddle for it here:-

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

like image 116
Kickstart Avatar answered Dec 09 '25 23:12

Kickstart