查找数据库中的数字范围中的间隙

时间:2018-04-18 07:37:20

标签: mysql sql

之前我已经发布了这个question如何找到数字范围之间是否存在数字。我能够使用下面的查询解决它

  SELECT count(StartingNumber) FROM range
  WHERE 690  BETWEEN   StartingNumber and EndingNumber
    or 1800  BETWEEN   StartingNumber and EndingNumber
    or StartingNumber in ( SELECT StartingNumber
                            FROM range
                            WHERE StartingNumber BETWEEN 690 AND 1800);

现在我只是想知道是否有可能找到各种数字范围的差距:

因此,如果范围从 1 - 100,101 - 135,150 - 200,201 - 255,255 - 270,301 - 326

我想找出缺失的范围 136 - 149,217 - 300 等。 DB表格列的图形表示如下所示:

enter image description here

现在我试图找出是否可以编写一个SQL查询,列出缺少的范围 251 - 299 1251 - 1299

2 个答案:

答案 0 :(得分:1)

试试这个

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.messages = [
    {
    'name' : 'asd',
    'weight' : '19'
     },
      {
    'name' : 'asd',
    'weight' : '21'
     },
      {
    'name' : 'asd',
    'weight' : '26'
     },
      {
    'name' : 'dsa',
    'weight' : '17'
     }
  ];
   $scope.expand = function(select) {

                    var boolexpansion = !select.expanded;

                    angular.forEach($scope.messages, function(n) {
                        n.expanded = false;
                    });
                    if(boolexpansion) {
                        select.expanded = !select.expanded;
                    }
                }
});

dbfiddle demo

子查询找到select * from ( select d1.hi + 1 tlo, min(d2.lo) - 1 thi from data d1 join data d2 on d1.hi < d2.lo group by d1.hi ) t where tlo < thi hi之间的范围,外部查询只选择正确的范围。

答案 1 :(得分:1)

好吧,你可以使用subquery? cols来指定你的实际数据排序

select * from (
    select *, (select idto 
               from table 
               where ? < t.? 
               order by ? desc LIMIT 1)+1 as MissingFrm,
           idfrm-1 as MissingTo
     from table t
)tt where idfrm <> MissingFrm;