我正在使用Codeigniter的汽車租賃系統,其中車輛可能有多個不可用的日期範圍。我爲不可用的日期範圍創建了單獨的表格,現在我希望用戶輸入日期範圍並選擇所有不與這些車輛的不可用日期範圍重疊的車輛。以下是我的代碼。MySQL檢查日期範圍是否與其他日期範圍重疊?
$d1 = date('Y-m-d', strtotime($pickup));
$d2 = date('Y-m-d', strtotime($dropoff));
// $this->db->where($d1." NOT BETWEEN date_ranges.start_date AND date_ranges.end_date AND " . $d2.' NOT BETWEEN date_ranges.start_date AND date_ranges.end_date');
$this->db->where("'$d1' NOT BETWEEN date_ranges.start_date AND date_ranges.end_date AND '$d2' NOT BETWEEN date_ranges.start_date AND date_ranges.end_date OR ('$d1' < date_ranges.start_date AND '$d2' > date_ranges.end_date) ");
// $this->db->where(" '$d1' <= date_ranges.end_date AND date_ranges.start_date <= '$d2'");
$query = ->join('date_ranges', 'vehicles.id = date_ranges.vehicle_id', 'left')
->group_by('vehicles.id')
->get('vehicles');
原始查詢
SELECT `vehicles`.`id`, `vehicles`.`year-`, `vehicles`.`model`,
`vehicles`.`nightly_rate`, `vehicles`.`class`,
`vehicle_pictures`.`picture`,
`vehicles`.`people` FROM `vehicles` LEFT JOIN `vehicle_pictures` ON
`vehicles`.`id` = `vehicle_pictures`.`vehicle_id` LEFT JOIN `date_ranges`
ON
`vehicles`.`id` = `date_ranges`.`vehicle_id`
WHERE (`country` LIKE '%%'
ESCAPE
'!' OR `state` LIKE '%%' ESCAPE '!' OR `city` LIKE '%%' ESCAPE '!' OR
`street`
LIKE '%%' ESCAPE '!' OR `zip` LIKE '%%' ESCAPE '!')
AND '2017-05-23'
NOT
BETWEEN `date_ranges`.`start_date` AND date_ranges.end_date AND '2017-
05-24'
NOT
BETWEEN `date_ranges`.`start_date` AND date_ranges.end_date OR ('2017-
05-23' <
`date_ranges`.`start_date` AND '2017-05-24' > date_ranges.end_date) AND
`vehicles`.`people` > '1' GROUP BY `vehicles`.`id`;
的[檢查日期範圍重疊在MySQL]可能的複製(https://stackoverflow.com/questions/2545947/check-overlap-of-date-ranges-in-mysql) – JazZ