gpt4 book ai didi

mysql - 基于可用性的查询的 SQL 连续出现

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

我在尝试创建一个相当复杂的 SQL(更具体地说是 MySQL)时遇到了困难。

数据库涉及汽车租赁,雪花图案的主表看起来有点像:

  id   | rent_start | rent_duration | rent_end     |  customerID |    carId
-----------------------------------------------------------------------------------
203 | 2016-10-03 | 5 | 2016-11-07 | 16545 | 4543
125 | 2016-10-20 | 9 | 2016-10-28 | 54452 | 5465
405 | 2016-11-01 | 2 | 2016-01-02 | 43565 | 346

我的目标是创建一个允许给定的查询

1) 时段范围,例如:从 2016-10-03 到 2016-11-03 2)天数,例如:10

允许我检索 10 月 10 日至 11 日之间至少连续 10 天实际可用的汽车。 这些汽车的 ID 列表已经足够了...我只是不知道如何设置这样的查询。

如果有帮助:我在另一个表中确实有所有汽车 ID 的列表。

无论如何,谢谢!

最佳答案

我认为为此目的,利用可用性比租赁要简单得多。

所以:

select r.car_id, r.rent_end as avail_start,
(select min(r2.rent_start
from rentals r2
where r2.car_id = r.car_id and r2.rent_start > r.rent_start
) as avail_end
from rentals r;

那么,对于您的查询,您至少需要 10 天。您可以使用 having 子句或子查询来实现此目的:

select r.*
from (select r.car_id, r.rent_end as avail_start,
(select min(r2.rent_start
from rentals r2
where r2.car_id = r.car_id and r2.rent_start > r.rent_start
) as avail_end
from rentals r
) r
where datediff(avail_end, avail_start) >= $days;

最后,您需要该时间段在您指定的日期内:

select r.*
from (select r.car_id, r.rent_end as avail_start,
(select min(r2.rent_start
from rentals r2
where r2.car_id = r.car_id and r2.rent_start > r.rent_start
) as avail_end
from rentals r
) r
where datediff(avail_end, avail_start) >= $days and
( (avail_end > $end and avail_start < $start) or
(avail_start <= $start and avail_end >= $start + interval 10 day) or
(avail_start > $start and avail_start + interval 10 day <= $end)
);

这可以处理免费期覆盖整个范围或在该范围内开始/结束的各种条件。

毫无疑问,这个逻辑中存在相差一的错误(汽车是否在返回的同一日期可用)。这应该为您提供解决问题的可靠方法。

顺便说一下,您还应该包括从未租过的汽车。但这对于您在问题中描述的表格是不可能的。

关于mysql - 基于可用性的查询的 SQL 连续出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40073347/

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