Mysql选择有时差的记录



我有一个表:

ID  DATE
1   2013-08-12 08:59:16
2   2013-08-13 08:59:16
3   2013-08-14 08:59:16
4   2013-08-17 08:59:16

我想选择日期差异在36小时内的记录,而不是当前日期

在上面的例子中,12日和13日是一种情况,13日和14日是另一种情况。

如果问题不清楚,很抱歉,但这是纯mysql

您可以为此使用相关的子查询。以下获取前一行或下一行36小时内的任何一行:

select t.*
from t
where exists (select 1
              from t t2
              where t2.id <> t.id and
                    t2.date between t.date - interval 36 hour and t.date + interval 36 hour
             );

您可以使用这样的查询:

SELECT
  t1.ID id1,
  t1.`date` date1,
  t2.ID id2,
  t2.`date` date2
FROM
  tablename t1 INNER JOIN tablename t2
  ON
    t1.id!=t2.id AND
    t2.`date` BETWEEN t1.`date` AND t1.`date`+ INTERVAL 36 HOUR

请看这儿的小提琴。

你可以做这样的事情(小编辑:OP在我的回答后只提到了sql部分):

$result = $connection->query("SELECT id,date FROM tablename");
while($thisRow= $result->fetch_assoc() ){
    $nextQuery = "SELECT id,date FROM tablename 
                  WHERE date>".$thisRow['date']." AND date<=".strtotime($thisRow['date']."+ 1 day")."
                  LIMIT 1";
    $next= connection->query($nextQuery);
    if($next->num_rows!==0){
        /* This line and the next line match
           $thisRow has info about current line
           $fetchNext has info about next line */
        $fetchNext = $next->fetch_assoc();
    }
}

最新更新