简体   繁体   English

MySQL找到密集的系列缺口

[英]Mysql find dense series gaps

I have a "sequence" column of a Mysql table with a unique key, this should start from value of 1 to n. 我有一个带有唯一键的Mysql表的“序列”列,它应该从1到n的值开始。

create table myTest( id INT, ...,  sequence INT ..)

This column should represents a dense serie, so I don't want gaps into it, my question is: how can I find possible gaps? 该列应代表一个密集的系列,因此我不希望出现任何缝隙,我的问题是: 如何找到可能的缝隙?

My first idea is to insert into a temporary 1 column table all values from 1 to max(sequence) with a loop. 我的第一个想法是使用循环将从1max(sequence)的所有值插入到临时1列表中。

create temporary table allvalues( value INT)

Then select all elems of this temp table where values are not in myTest table: 然后选择此临时表的所有元素,其中值不在myTest表中:

select value from allvalues where value is not in (select sequence from myTest)

Is there any other better/fastest solution? 还有其他更好/最快的解决方案吗?

This another idea, this doesn't find every gap but only the ending gap in case of contiguous gaps: 这是另一个想法,在连续的间隙的情况下,不会找到每个间隙,而只会找到末端的间隙:

select m1.sequence-1 from myTest m1
where m1.sequence>1 and not exists
  (select * from myTest m2 where m2.sequence=m1.sequence-1)

http://sqlfiddle.com/#!9/64f32/1 http://sqlfiddle.com/#!9/64f32/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM