SELECT MIN(p.num) AS "From",case when ((select min(t3.k)
from (SELECT k
FROM (
SELECT t1.num +1 AS "k"
FROM table1 t1
JOIN table1 t2 ON t1.num < t2.num
GROUP BY t1.num
HAVING t1.num +1 < MIN( t2.num )
)b
) t3
where t3.k>p.num limit 1) - 1) is null then
(select max(q.num) from table1 q)
else ((select min(t3.k)
from (SELECT k
FROM (
SELECT t1.num +1 AS "k"
FROM table1 t1
JOIN table1 t2 ON t1.num < t2.num
GROUP BY t1.num
HAVING t1.num +1 < MIN( t2.num )
)b
) t3
where t3.k>p.num limit 1) - 1) END as "to"
FROM table1 p
group by 2
SELECT p.num AS "From",(select min(t3.k)
from (SELECT k
FROM (
SELECT t1.num +1 AS "k"
FROM table1 t1
JOIN table1 t2 ON t1.num < t2.num
GROUP BY t1.num
HAVING t1.num +1 < MIN( t2.num )
)b
) t3
where t3.k>p.num limit 1) - 1 as "to"
FROM table1 p