我正在尝试修改从DB返回特定日期和时间之间的行的现有代码。它做得很好,但我想添加一个如下所述的功能。
这是我的数据库的一个例子
start end
1st row 2012-07-24 18:00:00 2012-07-28 17:00:00
2nd row 2012-07-25 19:00:00 2012-07-30 19:00:00
3rd row 2012-07-25 22:00:00 2012-07-28 13:00:00
4th row 2012-07-25 23:40:00 2012-07-27 18:00:00
...
...
...
当我的输入为2012-07-25 23:00:00BETWEEN start AND end ORDER by start DESC
时
结果是,
3rd row
2nd row
1st row
在这里之前一切都很好。但是,我想在列表顶部列出将在接下来的2小时内开始的任何行。这是第4行。
我试着用
ABS(TIMESTAMPDIFF( HOUR , `start`, :time )) < 2
不幸的是,我找不到解决方案。
以下是我的代码,从现在起,任何帮助都将不胜感激。(我使用3个变量,selected
、city
和type
)
// Store where clauses and values in arrays
$values = $where = array();
if (!empty($selected)) { //
$where[] = ':selected BETWEEN `start` AND `end`';
$values[':selected'] = $selected;
}
if (!empty($city)) { //
$where[] = '`city` = :city';
$values[':city'] = $city;
}
if (!empty($type)) { //
$where[] = '`type` = :type';
$values[':type'] = $type;
}
// Build query
$question = 'SELECT * FROM `events`';
if (!empty($where)) {
$question .= ' WHERE '.implode(' AND ', $where);
$question .= ' ORDER BY `start` DESC';
}
$query = $db->prepare($question);
$query->execute($values);
我没有检查参数的顺序,所以我把条件倒过来了。然而,我最初的发言仍然有效。基本上,最简单的答案是调整你的开始时间,就像这样:
SELECT *
FROM TMP
WHERE startedAt < DATE_ADD(TIMESTAMP('2012-07-25 23:00:00'), INTERVAL 2 HOUR)
AND endedBy >= TIMESTAMP('2012-07-25 23:00:00')
ORDER BY startedAt DESC
并有一个工作的例子。
您需要一个OR,以便事件在接下来的两个小时内开始
例如
where type = :type and city = :city and
((:selected BETWEEN `start` AND `end`) or
(`start` between :selected and adddate(:selected, interval 2 hours))
)
order by `start` desc