Mysql选择具有小时差异的记录

时间:2013-08-12 13:44:13

标签: 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

3 个答案:

答案 0 :(得分:3)

您可以为此使用相关子查询。以下内容在前一行或下一行的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
             );

答案 1 :(得分:2)

你可以使用这样的查询:

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

请参阅小提琴here

答案 2 :(得分:0)

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

$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();
    }
}