gpt4 book ai didi

php - MySQL 检查日期范围是否与其他日期范围重叠?

转载 作者:行者123 更新时间:2023-11-29 18:55:28 25 4
gpt4 key购买 nike

我正在使用 Codeigniter 开发一个汽车租赁系统,其中车辆可以有多个不可用的日期范围。我已经为不可用的日期范围创建了一个单独的表,现在我希望用户输入一个日期范围并选择与这些汽车的不可用日期范围不重叠的所有汽车。以下是我的代码。

    $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`;

最佳答案

不重叠的日期范围的基本算法是:

NOT(unavailable_date_range_START <= desired_date_range_END) AND NOT(unavailable_date_range_END >= desired_date_range_START)

所以翻译成你的查询,它应该是这样的:

 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`)

WHERE ( `country` LIKE '%%' ESCAPE '!'
OR `state` LIKE '%%' ESCAPE '!'
OR `city` LIKE '%%' ESCAPE '!'
OR `street` LIKE '%%' ESCAPE '!'
OR `zip` LIKE '%%' ESCAPE '!')
AND `vehicles`.`id` NOT IN(SELECT DISTINCT `date_ranges`.`vehicle_id`

FROM `date_ranges`

WHERE `date_ranges`.`start_date` <= '$d2' AND `date_ranges`.`end_date` >= '$d1')

关于php - MySQL 检查日期范围是否与其他日期范围重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44153943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com