0

令人困惑,但是,情况如下:

我们有序列号,对应于程序每隔 1 分钟所在的位置。

Sequence#  |  Timestamp
   1       |   2012-04-11 12:00:00
   2       |   2012-04-11 12:01:00
   2       |   2012-04-11 12:02:00
   2       |   2012-04-11 12:03:00
   3       |   2012-04-11 12:04:00
   5       |   2012-04-11 12:05:00
   5       |   2012-04-11 12:06:00
   6       |   2012-04-11 12:07:00
   1       |   2012-04-11 12:08:00
   2       |   2012-04-11 12:09:00
   2       |   2012-04-11 12:10:00
   2       |   2012-04-11 12:11:00
   3       |   2012-04-11 12:12:00

序列的持续时间可能会改变,但间隔始终相同(精确地每 1 分钟一次)。

如您所见,序列重复。如何找到Seqence的最新开始出现n

所以,如果我想搜索序列 2,我会想要返回2 | 2012-04-11 12:09:00,因为它是序列 2 的最新开始出现。

4

4 回答 4

4

尝试:

SELECT t1.* FROM `table_name` t1
LEFT JOIN `table_name` t2 
on t1.`Sequence` = t2.`Sequence` and 
   t1.`Timestamp` = t2.`Timestamp` + interval 1 minute
WHERE t1.`Sequence`=2 and t2.`Sequence` is null
ORDER BY t1.`Timestamp` DESC LIMIT 1

SQLFiddle在这里

于 2013-04-11T16:35:29.787 回答
0

这是你想要的吗?

$desired_sequence=2;

$query="SELECT * FROM `table_name` ORDER BY `Timestamp` DESC";
$result = mysql_query($query);
if (mysql_errno()) { die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) ); }

$found_desired=0;
while($row = mysql_fetch_array($result))
{
    if($row['Sequence']==$desired_sequence)
    {
        $found_desired=1;
        $timestamp=$row['Timestamp'];
    }

    if( ($found_desired==1) && ($row['Sequence']!=$desired_sequence) )
    {
        return; // End the while loop because $timestamp will have your desired output.
    }
}
于 2013-04-11T16:47:58.027 回答
0

我不确定你到底想要什么。如果数据在文本文件中,我编写了一些代码。如果数据在数据库中,那就更容易了。但是,我假设因为在您的示例中您有一个 | 分离不在数据库中的数据。

function findLastOccurenceOfSequence ($sequenceNumber)
{
    if (@!is_int ($sequenceNumber))
        throw new Exception ("Expected param1 to be an integer");
    $data = file_get_contents ("testFile.txt");
    $dataArray = explode ("\n", $data);
    $dataArray = array_reverse ($dataArray);
    $returnLine = "";
    $sequenceStarted = false;
    foreach ($dataArray as $key => &$dataLine)
    {
        $pieces = explode ("|", $dataLine);
        if (count ($pieces) != 2)
            continue;
        list ($thisSequenceNum, $timeStamp) = $pieces;
        $thisSequenceNum = intval (trim ($thisSequenceNum));
        if ($thisSequenceNum == $sequenceNumber)
        {
            $sequenceStarted = true;
            $returnLine = $dataLine;
        }
        else if ($sequenceStarted)
        {
            break;
        }
    }

    if ($key == count ($dataArray))
    {
        throw new Exception ("Sequence not found!");
    }

    return $returnLine;
}

echo "OCCURRENCE: " . findLastOccurenceOfSequence (2);
于 2013-04-11T17:02:39.907 回答
0

我想这就是你想要的...

SELECT * FROM `table_name` WHERE `Sequence`=2 ORDER BY `Timestamp` DESC LIMIT 1
于 2013-04-11T16:26:57.873 回答