我有以下记录的 table 预订。
event_type | from_date | to_date
-------------+---------------------+---------------------
party | 2015-09-24 08:00:00 | 2015-09-24 09:30:00
hangout | 2015-09-24 09:00:00 | 2015-09-24 10:00:00
hangout | 2015-09-24 10:00:00 | 2015-09-24 10:30:00
dinner | 2015-09-24 12:00:00 | 2015-09-24 13:30:00
因此,当用户在前端选择日期和时间时,我将发送一个带时间的日期作为上面的示例。
现在在后端,我正在考虑使用用户选择的日期和时间查询所有记录。
因此,如果选择的日期和时间存在(查询返回大于 0),那么我将显示预订不可用,但如果它返回 0 记录,则预订可用。
我怎样才能做到这一点?
回答1
如果前端给出两个日期和事件类型:
- fe_period_start
- fe_period_end
- fe_event_type
然后查询以检查是否没有重叠时段应该如下所示
select count(*) from booking
where event_type = fe_event_type
and from_date <= fe_period_end
and to_date >= fe_period_start
在这种情况下,我们发现预订在 10:00 结束并且我们从 10:00 开始寻找免费的情况也存在冲突。
如果我们接受,一个预订可以在 10:00 结束,第二个预订可以在 10:00 开始,那么 where
中的不等式一定很严重。
select count(*) from booking
where event_type = fe_event_type
and from_date < fe_period_end
and to_date > fe_period_start