初始化数据
# 创建表 DROP TABLE IF EXISTS g; CREATE TABLE g( a INT )ENGINE=INNODB; # 初始化数据 INSERT INTO g SELECT 1; INSERT INTO g SELECT 2; INSERT INTO g SELECT 3; INSERT INTO g SELECT 100; INSERT INTO g SELECT 101; INSERT INTO g SELECT 103; INSERT INTO g SELECT 104; INSERT INTO g SELECT 105; INSERT INTO g SELECT 106;
对于g表其缺失范围如4-16所示
对于g表其连续范围如4-17所示
对于缺失范围的问题,可以通过下列步骤来解决
1)找到间断点之前的值,然后对该值加1,即为start_range;
2)找到间断点之前的值,然后对该值减1,即为end_range;
对于间断点之前的值,可以用如下sql:
SELECT a FROM g AS A WHERE NOT EXISTS( SELECT * FROM g AS B WHERE A.a+1=B.a )
查出的106是无用的,因为它是表中的最大值,所以将其过滤掉。断点之前的值,对该值加1操作,即为start_range,可以通过以下sql语句得到:
SELECT a+1 start_range FROM g AS A WHERE NOT EXISTS( SELECT * FROM g AS B WHERE A.a+1=B.a ) AND a < (SELECT MAX(a) FROM g)
最后通过子查询为每个最小间断点返回表g中下一个已有的值并减一,即得到间断点end_range,最终sql语句如下所示:
SELECT a+1 start_range, ( SELECT MIN(a)-1 FROM g C WHERE C.a > A.a ) AS end_range FROM g AS A WHERE NOT EXISTS( SELECT * FROM g AS B WHERE A.a+1=B.a ) AND a < (SELECT MAX(a) FROM g)
这只是该问题的解决方案之一,更为简单直观的方法是,将表g中的数据进行移位匹配,如果是连续的值,那么其差值应该为1,如果不是连续的值就应该大于1。
~~待更新
时间: 2024-10-08 16:15:04