时间段可用多天mysql

时间:2012-12-21 08:42:25

标签: mysql calendar

我对MySQL中的空闲时隙检索有疑问。我有2个表。

 Table 1:
 TimeSlots (Defines the available timeslots in 15 minutes)

 Columns : StartTime (**Time**), EndTime(**Time**)
 Data:

 00:00:00 , 00:15:00
 00:15:00 , 00:30:00
 And so on until 23:45:00 , 00:00:00

表2计划程序(保留计划任务)

 Columns : idScheduler (**pk**) , Room (**int, fk**), StartDateTime (**DateTime**), EndDateTime (**DateTime**)

我用来检索一天的开放时间的查询是:

     SELECT StartTime, EndTime FROM TimeSlots WHERE 
     NOT Exists (                
            SELECT Room, StartDateTime, EndDateTime FROM Scheduler
        WHERE Room = 'Room1'
        AND DATE(StartDateTime) =  '2012-12-20'
        AND 
            (StartDateTime >= concat('2012-12-20', ' ' ,StartTime) AND
            StartDateTime <= concat('2012-12-20', ' ' ,EndTime))
            OR
            (EndDateTime >= concat('2012-12-20', ' ' ,StartTime) AND
            EndDateTime <= concat('2012-12-20', ' ' ,EndTime))
            OR
            (EndDateTime <= concat('2012-12-20', ' ' ,StartTime) AND
            StartDateTime >= concat('2012-12-20', ' ' ,EndTime))
        )

Room和StartDateTime将成为最终解决方案中的参数。

我遇到的问题是,如果房间被预订,例如跨越多个时段 (例如:1,1,2012-12-20 13:10:00,12012-12-20 13:55:00)

如果我运行上面提到的查询,它将提供此输出:

13:00:00 - 13:15:00
13:15:00 - 13:30:00
13:30:00 - 13:45:00
13:45:00 - 14:00:00

我在这里缺少什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情:

SELECT StartTime, EndTime FROM TimeSlots WHERE 
 NOT Exists (                
        SELECT Room, StartDateTime, EndDateTime FROM Scheduler
    WHERE Room = 'Room1'
    AND DATE(StartDateTime) =  '2012-12-20'
    AND 
        (StartDateTime <= concat('2012-12-20', ' ' ,EndTime) AND
        EndDateTime >= concat('2012-12-20', ' ' ,StartTime))
    )

通过这种方式,您需要一个与任何房间预订不相交的时间段。

相关问题