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

mbzjlibv  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(409)

这个问题在这里已经有答案了

mysql检查日期范围是否在日期范围内(1个答案)
mysql:检查日期范围(2个答案)
两年前关门了。
我有以下代码,它运行良好:

$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_start 以及 event_end 存储为int。
我试过使用between,但是我不确定在代码中到底应该把between放在哪里。

d4so4syb

d4so4syb1#

对于针对单个日期字段的查询,可以使用 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 .

qlfbtfca

qlfbtfca2#

使用 BETWEEN ( column 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";

相关问题