如何在mysql中找到顺序编号中的空白? [英] How to find gaps in sequential numbering in mysql?

查看:179
本文介绍了如何在mysql中找到顺序编号中的空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个带有表的数据库,该表的值是从另一个系统导入的.有一个自动增量列,没有重复的值,但缺少值.例如,运行以下查询:

We have a database with a table whose values were imported from another system. There is an auto-increment column, and there are no duplicate values, but there are missing values. For example, running this query:

select count(id) from arrc_vouchers where id between 1 and 100

应返回100,但应返回87.我可以运行任何查询来返回缺失数字的值吗?例如,可能存在ID为1-70和83-100的记录,但是没有ID为71-82的记录.我想返回71、72、73等

should return 100, but it returns 87 instead. Is there any query I can run that will return the values of the missing numbers? For example, the records may exist for id 1-70 and 83-100, but there are no records with id's of 71-82. I want to return 71, 72, 73, etc.

这可能吗?

推荐答案

更新

ConfexianMJS在性能方面提供了 好得多 answer

以下版本适用于任何大小的表(不仅限于100行):

Here's version that works on table of any size (not just on 100 rows):

SELECT (t1.id + 1) as gap_starts_at, 
       (SELECT MIN(t3.id) -1 FROM arrc_vouchers t3 WHERE t3.id > t1.id) as gap_ends_at
FROM arrc_vouchers t1
WHERE NOT EXISTS (SELECT t2.id FROM arrc_vouchers t2 WHERE t2.id = t1.id + 1)
HAVING gap_ends_at IS NOT NULL

  • gap_starts_at-当前间隙中的第一个ID
  • gap_ends_at-当前间隔中的最后一个ID
    • gap_starts_at - first id in current gap
    • gap_ends_at - last id in current gap
    • 这篇关于如何在mysql中找到顺序编号中的空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆