Mysql
 sql >> Database >  >> RDS >> Mysql

Come trovare i numeri di serie senza interruzioni in MySQL?

Ha avuto più di un gioco:-

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 per questo qui:-

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