MYSQL在开始结束日期日期格式d-m-Y之间选择

时间:2018-01-24 09:27:52

标签: php mysql database date select

如果我在MYSQL中这样做,它可以工作:

    SELECT * FROM reservations
WHERE
reservationStartDate >= '2018-01-01' 
AND
reservationEndDate <= '2018-02-16'
AND
reservationSpace = 'kantoor-1'

所以我想制作一个这样的函数:

        public function checkReservations($startdate, $enddate, $workspace, $bind="") {
            //SELECT * FROM reservations WHERE reservationStartDate >= '2018-01-19' AND reservationEndDate <= '2018-02-01' AND reservationSpace = 'kantoor-1';
            // Date format = 2018-12-31
    $sql = "
            SELECT * FROM apolloworkspaces.reservations
            WHERE
            reservationStartDate >= '".$startdate."' 
            AND
            reservationEndDate <= '".$enddate."'
            AND
            reservationSpace = '".$workspace."'
            "
            ;               
    $this->run($sql,$bind);
}       

在php中我使用:

$test2 = $db->checkReservations('2018-01-01', '2018-02-16', 'kantoor-1');

echo '<pre>'.print_r($test2,true).'</pre>';

它显示什么都没有......我几乎在那里,我已经将日期的格式更改为Y-m-d

3 个答案:

答案 0 :(得分:1)

您可以使用STR_TO_DATE MySQL函数:

SELECT * FROM reservations 
WHERE reservationStartDate 
BETWEEN STR_TO_DATE('22-01-2018', '%d-%m-%Y') 
        AND STR_TO_DATE('03-02-2018', '%d-%m-%Y')

BETWEEN STR_TO_DATE

BETWEENreservationStartDate >= '22-01-2018' AND reservationStartDate <= '03-02-2018'的更好形式(也就速度而言)但是你的情况只适用STR_TO_DATE将'dmY'字符串转换为实际日期格式让MySQL来处理它。

DATE类型字段

您可以做的最好的事情是使用DATE类型字段来存储日期,因此您不再需要STR_TO_DATE

答案 1 :(得分:0)

如果您需要在日期范围内从MySQL database表中选择行,则需要使用如下命令:

SELECT * FROM table 
WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';

您可以使用STR_TO_DATE()将字符串转换为MySQL日期值:

SELECT * FROM reservations 
WHERE reservationStartDate BETWEEN STR_TO_DATE('22-01-2018', '%d-%m-%Y') AND STR_TO_DATE('03-02-2018', '%d-%m-%Y')

但是,最好将列转换为DATE data type而不是使用字符串。

答案 2 :(得分:0)

试试这个:

SELECT * FROM reservations WHERE reservationStartDate >= '22-01-2018' 
AND reservationEndDate<= '03-02-2018'