MySQL - DATE_SUB()和DATE_SUB()之间的搜索查询错误

时间:2013-03-26 23:41:58

标签: php mysql date

我正在尝试使用DATE_SUB()在日期范围(日期7天)和(日期1天)之间进行搜索查询(使用pdo php和mysql),例如:

end_date is 2013-03-26
search between 2013-03-19 and 2013-03-25 ` 

以下查询使用第一个date_sub(7天间隔)但忽略第二个(date_sub(1天间隔),以便在2013-03-19和2013-03-26之间进行搜索。

$sevd_query = " 
    SELECT 
        booking_id,
        DATE_FORMAT(start_date, '%e/%c') AS s_d,
        DATE_FORMAT(end_date, '%e/%c') AS e_d
    FROM 
        bsi_bookings as bb 
    INNER JOIN 
        bsi_reservation as br ON bb.booking_id=br.bookings_id
    WHERE 
        bc.c_id=:c_id AND
       :day BETWEEN DATE_SUB(bb.end_date, INTERVAL 7 DAY) AND DATE_SUB(bb.end_date, INTERVAL 1 DAY)
";

有人可以帮忙吗?我一直试图解决这个问题一个星期没有运气

1 个答案:

答案 0 :(得分:0)

条款:

:day BETWEEN DATE_SUB(bb.end_date, INTERVAL 7 DAY) AND
             DATE_SUB(bb.end_date, INTERVAL 1 DAY)

可表示为:

day >= (end_date - 7) AND
day <= (end_date - 1)

可以改写为:

(day + 7) >= end_date AND
(day + 1) <= end_date

与:

相同
end_date <= (day + 7) AND
end_date >= (day + 1)

也是:

end_date >= (day + 1) AND
end_date <= (day + 7)

也可以写成:

end_date BETWEEN (day + 1) AND (day + 7)

我认为不是你想要的。

请改为尝试:

SELECT 
    booking_id,
    DATE_FORMAT(start_date, '%e/%c') AS s_d,
    DATE_FORMAT(end_date, '%e/%c') AS e_d
FROM 
    bsi_bookings as bb 
INNER JOIN 
    bsi_reservation as br ON bb.booking_id=br.bookings_id
WHERE 
    bc.c_id=:c_id AND
    bb.end_date BETWEEN :day - INTERVAL 7 DAY AND :day - INTERVAL 1 DAY;

如果end_date字段已编入索引,则将允许使用索引。

如果要搜索的字段包含在函数内,则不会使用索引。