gpt4 book ai didi

mysql - 在预订表中找到足够大的差距

转载 作者:可可西里 更新时间:2023-11-01 07:02:05 26 4
gpt4 key购买 nike

租赁系统使用预订表来存储所有预订和预订:

booking | item | startdate        | enddate
1 | 42 | 2013-10-25 16:00 | 2013-10-27 12:00
2 | 42 | 2013-10-27 14:00 | 2013-10-28 18:00
3 | 42 | 2013-10-30 09:00 | 2013-11-01 09:00

假设用户想从 2013-10-27 12:00 到 2013-10-28 12:00 租用项目 42,这是一天的时间段。系统会告诉他,该元素在给定的时间范围内不可用,因为预订编号。 2 碰撞。

现在我想建议所选项目再次可用时的最早租赁日期和时间。当然,从用户期望的日期和时间开始考虑用户请求的时间段(1 天)。

所以在上面的例子中,我正在寻找一个返回 2013 年 10 月 28 日 18:00 的 SQL 查询,自 2013 年 10 月 27 日 12:00 以来项目 42 可用于 1 的最早日期日期,从2013-10-28 18:00到2013-10-29 18:00。

因此我需要找到预订之间的间隔,该间隔要大到足以保留用户的预订,并且尽可能接近所需的开始日期。

或者换句话说:我需要找到给定项目的第一个预订,之后有足够的空闲时间来进行用户的预订。

这是否可以在纯 SQL 中实现,而不必遍历每个预订及其后续预订?

最佳答案

如果您不能重新设计您的数据库以使用更高效的东西,这将得到答案。你显然想要参数化它。它说找到所需的日期,或者租用间隔与现有预订不重叠的最早结束日期:

Select
min(startdate)
From (
select
cast('2013-10-27 12:00' as datetime) startdate
from
dual
union all
select
enddate
from
booking
where
enddate > cast('2013-10-27 12:00' as datetime) and
item = 42
) b1
Where
not exists (
select
'x'
from
booking b2
where
item = 42 and
b1.startdate < b2.enddate and
b2.startdate < date_add(b1.startdate, interval 24 hour)
);

Example Fiddle

关于mysql - 在预订表中找到足够大的差距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529276/

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