分享两张桌子:
汽车
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
第一张表是汽车列表,其中count是此型号的汽车数量。 第二张表是汽车预订清单。
问题:
用户输入两个日期,系统必须提供这些日期之间可用的汽车列表
我想要的是,用户输入的日期和第二张表中预订车辆的日期,确定这些日期预订了多少辆汽车。
在某些情况下,汽车在日期之间部分保留,在这种情况下,汽车也需要被视为预订。
如何通过一个sql请求来接收可用的列表和数量
汽车?
car_id | count_available
答案 0 :(得分:1)
这是典型的重叠查询。您可以使用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
);
当一个在第二个结束之前开始而第一个在第二个结束之后结束时,会出现两个时间帧之间的重叠。
请注意,<=
和>=
可能真的是<
和/或>
,具体取决于您计算期末的结果。
答案 1 :(得分:1)
怎么样?
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;
编辑:如下所示改为&lt; =和&gt; =。