有两个表:
汽车
id | name | count_cars
1 | Volvo S60 | 3
2 | Tesla model 3 | 2 预约
id | car_id | date_from | date_to
1 | 1 | 2017-05-02 10:00 | 2017-05-05 10:00
2 | 1 | 2017-05-01 10:00 | 2017-05-03 10:00
3 | 2 | 2017-05-03 10:00 | 2017-05-04 10:00 第一个表是cars list,其中count是该车型的汽车数量。第二个表是预订汽车的列表。
问题:
用户输入两个日期,系统必须提供在这两个日期之间可用的汽车列表。
我希望,有了用户输入的日期和第二个表中预订汽车的日期,就可以确定这些日期预订了多少辆汽车和哪些汽车。
在某些情况下,汽车在日期之间被部分预订,在这种情况下,汽车也需要被视为已预订。
如何通过一个sql请求来接收可用汽车的列表和数量?
car_id|count_available
发布于 2017-05-02 00:09:56
这是一个典型的重叠查询。您可以使用not exists
select c.*
from cars c
where not exists (select 1
from reservations r
where r.carid = c.id and
r.startdate <= $enddate and
r.enddate >= $startdate
);当一个时间帧在第二个结束之前开始,第一个结束在第二个开始之后时,两个时间帧之间会发生重叠。
请注意,<=和>=实际上可能是<和/或>,这取决于您如何计算句号末尾。
发布于 2017-05-02 00:10:28
那么,一个
SELECT r.car_id, count(r.car_id)
FROM cars c, reservations r
WHERE r.date_from <= :user_input_from
AND r.date_to >= :user_input_to
AND r.car_id = c.id group by r.car_id;编辑:如下所示,更改为<=和>=。
https://stackoverflow.com/questions/43722231
复制相似问题