在DATEDIFF查询中减去一天

时间:2015-08-27 08:26:05

标签: php mysql datediff

如果用户选择"2015-08-27 to 2015-08-29"之间的日期,则29被视为结帐日期,因此我想输出27&的费率。 28。

现在这段代码输出3天,只需要输出2天

数据库

enter image description here

$pdo = $dbo->prepare(
    "SELECT r.*, rr.rid, SUM(ABS(DATEDIFF(:ci, :co) * rr.rate)) as totalsum, rr.sdate, rr.edate 
    FROM rooms r 
    LEFT JOIN rates as rr ON r.id=rr.rid
    WHERE r.id NOT IN (SELECT room_id FROM reservation as b WHERE (b.checkout <= :ci 
    AND b.checkin >= :co) OR (b.checkout >= :ci AND b.checkin <= :co)) 
    AND (rr.sdate >= :ci AND rr.edate <=:co) OR (rr.sdate <=:ci AND rr.edate >=:co)
    GROUP BY rr.rid, r.room_name");                           
//$pdo->bindValue(':stat', 'confirm', PDO::PARAM_STR);
$pdo->bindParam(':ci', $check_in, PDO::PARAM_STR);
$pdo->bindParam(':co', $check_out, PDO::PARAM_STR);
if (!$pdo->execute()) {
    print_r($pdo->errorInfo());
} else {
    //Do something
}

3 个答案:

答案 0 :(得分:3)

您可能甚至不需要在查询中使用PHP来解决它:

DATE_SUB(final_date, INTERVAL 1 DAY)

这应该相当于(final_date - 1天)

答案 1 :(得分:2)

我只是从此

更改了我的check out string
$check_out =  date("Y-m-d" strtotime($_POST['co'])

$check_out = date("Y-m-d", strtotime('-1 day', strtotime($_POST['co'])));

并删除查询中的DATEDIFF() & ABS(),如下所示

SELECT r.*, rr.rid, SUM(rr.rate) as totalsum, rr.sdate, rr.edate 
FROM rooms r 
LEFT JOIN rates as rr ON r.id=rr.rid
WHERE rr.sdate >= :ci AND rr.edate <= :co
GROUP BY rr.rid, r.room_name

完成。

答案 2 :(得分:1)

在MySql中你可以使用简单的DATE_ADD(checkout_date,INTERVAL -1 DAY)。它会从你的结账日期减少1天 那么你可以正确计算日期差异

DATEDIFF(DATE_ADD(checkout_date,INTERVAL -1 DAY),checkin_Date)