在具有首选开始

时间:2017-05-15 03:18:19

标签: mysql sql

我有2张桌子......

约会:

id (int)
start (datetime)
end (datetime)

时隙:

id (int)
timeslot (time)

表格时间段有这样的记录......

00:00:00
00:05:00
00:10:00
...
23:55:00

表约会有一条记录......

start: 2017-05-15 01:30:00
end: 2017-05-15 02:00:00

使用以下简化查询,如果在尊重现有约会的同时没有优先的每小时开始时间,我会尝试每小时获得第一个免费的开始时间段...

SET @mandatory=true, @parallel=1, @targetdate="2017-05-15", @begin='30', @duration='00:30:00', @time_start="00:00:00", @time_end="03:00:00";
SELECT MIN(timeslot) AS free_slot FROM timeslots
INNER JOIN
appointments
ON 1=1
WHERE timeslots.timeslot BETWEEN @time_start AND @time_end
AND (ADDTIME(timeslot, @duration) BETWEEN @time_start AND @time_end)
AND ((@mandatory AND MINUTE(timeslot)=@begin) OR (NOT @mandatory))
AND ((
  SELECT COUNT(*) AS anzahl
  FROM appointments
  WHERE (concat(date(@targetdate)," ",timeslots.timeslot) BETWEEN appointments.start AND appointments.end - INTERVAL 1 SECOND
  OR concat(date(@targetdate)," ", ADDTIME(timeslot, @duration) ) BETWEEN appointments.start AND appointments.end - INTERVAL 1 SECOND)
) < @parallel)
GROUP BY HOUR(timeslot)

参数说明:

@mandatory: TRUE表示,我只允许时间段匹配@begin。 FALSE意味着,我更喜欢匹配@begin的(!)时隙,但如果没有匹配,我希望每小时获得第一个空闲时段。

@parallel: 允许的并行约会数。值1表示不应有重叠约会。值2表示同时应该只有2个约会。

@targetdate: 查询应仅返回targetdate的时隙。

@Begin: 自由时间段的首选开始。 &#39; 30&#39;意思是,我想让时间段开始&#34;一半过去......&#34;每小时。

@duration:连续免费时段所需的持续时间。

@time_start和@time_end: 结果应该只包含此时间范围内的记录。

我的问题是,我得到的是免费的时间段,只能在半个月开始......或者每一个小时的第一个空闲时间段 - 取决于将@mandatory设置为TRUE或FALSE。

当将@mandatory设置为TRUE时,我认为我得到了所需的结果(只有从定义的开始时间开始的时间段)。但是我想将@mandatory设置为FALSE并且每小时获得第一个免费时间段,只有在没有自由时间段开始的时候有一半(我想优先选择匹配的开始时隙,但是提供其他时间段......

这是我想要的:

00:30:00
01:00:00 (this row respects the existing appointment at half past one and returns the first free timeslot for this hour only when the duration of the remaining timeslots fits)
02:30:00

有没有简单的方法来获得这些结果?

祝你好运

0 个答案:

没有答案