更改SQL查询以查找日期范围之间的数据

时间:2018-09-13 00:20:51

标签: php mysql

我有以下代码,并且工作正常:

$time = time(); 
$todayint=date("Y-m-d", strval($time));

    $sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE DATE(FROM_UNIXTIME(event_start))='$todayint' OR DATE(FROM_UNIXTIME(event_end))='$todayint' ORDER BY event_organiser ASC"; 

如何更改代码以选择日期范围内的数据?

event_startevent_end存储为整数。

我尝试使用between,但是我不确定在代码之间的确切位置。

2 个答案:

答案 0 :(得分:1)

对于单个日期字段的查询,可以使用 BETWEEN 运算符:

$sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE 
        DATE(FROM_UNIXTIME(event_time)) BETWEEN '$date1' AND '$date2'
        ORDER BY event_organiser ASC"; 

对于针对多个日期字段(例如开始时间和结束时间)的查询,您需要检查=><=

$sql = "SELECT * FROM " . $DB->prefix('cal_event') . " WHERE 
        DATE(FROM_UNIXTIME(event_start)) >= '$todayint' AND
        DATE(FROM_UNIXTIME(event_end)) <= '$todayint'
        ORDER BY event_organiser ASC";

在两种情况下,您都希望使用AND而不是OR

答案 1 :(得分:1)

使用BETWEENcolumn BETWEEN value1 AND value2

$time = time(); 
$todayint=date("Y-m-d", strval($time));

$sql = "SELECT * FROM " . $DB->prefix('cal_event') 
     . "WHERE DATE(FROM_UNIXTIME(event_start))
        BETWEEN '$todayint' AND '$todayint'
        ORDER BY event_organiser ASC";

使用>=column >= value1 AND column <= value2

$time = time(); 
$todayint=date("Y-m-d", strval($time));

$sql = "SELECT * FROM " . $DB->prefix('cal_event') 
     . "WHERE DATE(FROM_UNIXTIME(event_start)) >= '$todayint'
        AND DATE(FROM_UNIXTIME(event_end)) <= '$todayint'
        ORDER BY event_organiser ASC";