2

我有一张桌子:

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

4

3 回答 3

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
             );
于 2013-08-12T14:05:33.807 回答
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

在此处查看小提琴。

于 2013-08-12T14:02:59.517 回答
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();
    }
}
于 2013-08-12T13:56:19.640 回答