MYSQL中的序列

时间:2016-06-06 22:56:55

标签: php mysql

有没有办法跟踪MYSQL中的连续数字子序列?

我想计算数字序列中最高的连续子序列:

1,2,3,4,6,7 => 4 (1-4)
1,2,3,4,5,6,8 => 6 (1-6)
1,2,3,5 => 3 (1-3)
1,2,3,5,6,7,8 => 4 (5-8)
1,2,4,5,6,8,9 => 3 (4-6)

2 个答案:

答案 0 :(得分:0)

根据您的问题,此代码应该有效:

function findHighestSeriesCount( $seriesArray )
{
    if ( 1 >= count( $seriesArray ) )
    {
        # catch the special case when array has only 0 or 1 element
        return count( $seriesArray );
    }
    $highestCount = -1;
    $currentCount = 1;
    $lastElement = $seriesArray [0];

    $getCorrectHighValue = function() use ( &$highestCount, &$currentCount )
    {
        return $highestCount < $currentCount ? $currentCount : $highestCount;
    };

    for ( $arrayIndex = 1 ; $arrayIndex < count( $seriesArray ) ; $arrayIndex++ )
    {
        if ( $lastElement + 1 == $seriesArray [$arrayIndex] )
        {
            $currentCount++;
        }
        else
        {
            $highestCount = $getCorrectHighValue();
            $currentCount = 1;
        }
        $lastElement = $seriesArray [$arrayIndex];
    }

    return $getCorrectHighValue();
}

测试脚本:

$seriesArray = [1,2,3,4,6,7];
echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesArray ), 
     findHighestSeriesCount( $seriesArray ) );

$seriesArray = [1,2,3,4,5,6,8];
echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesArray ), 
     findHighestSeriesCount( $seriesArray ) );

$seriesArray = [1,2,3,5];
echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesArray ), 
     findHighestSeriesCount( $seriesArray ) );

$seriesArray = [1,2,3,5,6,7,8];
echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesArray ), 
     findHighestSeriesCount( $seriesArray ) );

$seriesArray = [1,2,4,5,6,8,9];
echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesArray ), 
     findHighestSeriesCount( $seriesArray ) );

输出:

array=1,2,3,4,6,7 - highest count=4
array=1,2,3,4,5,6,8 - highest count=6
array=1,2,3,5 - highest count=3
array=1,2,3,5,6,7,8 - highest count=4
array=1,2,4,5,6,8,9 - highest count=3

答案 1 :(得分:0)

假设数据存储为列,您可以通过查找最长的连续序列来获取最大值。这个想法只是简单地减去另一个序列。 。 。在值不变的地方,你知道你有一个序列。

其余的只是聚合。这看起来像:

select count(*)
from (select t.*, (@rn := @rn + 1) as rn
      from t cross join (select @rn := 0) params
     ) t
group by (col - rn)
order by count(*) desc
limit 1;