令人困惑,但是,情况如下:
我们得到的序列号对应于程序以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的最新开始出现。
答案 0 :(得分: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 here。
答案 1 :(得分:0)
我认为这就是你想要的......
SELECT * FROM `table_name` WHERE `Sequence`=2 ORDER BY `Timestamp` DESC LIMIT 1
答案 2 :(得分: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.
}
}
答案 3 :(得分: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);