dragam0217 2013-07-25 14:56
浏览 285

Mysql,在序列中找到缺失的数字[重复]

This question already has an answer here:

I have a huge table with a couple hundred thousand records. They all have a unique id for the first column though some are missing in the sequence of numbers.

I am trying to show a list of the numbers that are missing individually.

So for example:

10029
10032
10034
10036

I am trying to get it to show:

10030
10031
10033
10035

I found this query but it seems to be missing numbers when there's a range:

SELECT t1.id+1 AS Missing 
FROM data AS t1 
LEFT JOIN data AS t2 
    ON t1.id+1 = t2.id 
WHERE t2.id IS NULL 

Result:

10030
10033

As you can see, 10031 and 10035 are missing from that list.

</div>
  • 写回答

1条回答 默认 最新

  • druybew06513 2013-07-25 15:04
    关注

    Perhaps something like this as a starting point. Not tested, but might just work

    SELECT @min := (SELECT min(id) FROM yourtable); // get the smallest ID in the table
    SELECT @last := @min; // cache the min value for the where clause
    
    SELECT id, id - @last AS difference, @last := id
    FROM yourtable
    WHERE id > @min
    ORDER BY id ASC
    HAVING difference > 1
    

    it won't give you the individual missing ids, but it'll tell you where the gaps are, and how big they are.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c