我正在尝试创建查询以列出特定日期的开放时间段。我在这里发现了很多类似的问题,但没有一个答案似乎可以完成这项工作。
查询只需要在特定时间段之间显示结果。例如,如果我想搜索一天的开放时间段,我会将开始日期设置为2017-03-17 08:00:00(上午8:00开放时间)和结束日期2017-03- 17 17:00:00(下午5:00是当天的关闭时间)。然后它必须查询当天并从我的约会表中返回打开的位置和预约的约会。 (注意:我不保存表中的开放槽或单独的表,这些将需要由查询生成。)
我预约的约会表的简化版本:
表名:registered_appointments (输出前)
+----------------------+---------------------+----------+
| start_time | end_time | duration |
+----------------------+---------------------+----------+
| 2017-03-17 10:45:00 | 2017-03-17 11:30:00 | 45 |
| 2017-03-22 09:30:00 | 2017-03-22 10:30:00 | 60 |
| 2017-03-24 08:45:00 | 2017-03-24 11:30:00 | 165 |
| 2017-03-22 11:30:00 | 2017-03-22 12:30:00 | 60 |
+----------------------+---------------------+----------+
我当前的MYSQL查询:(我从另一个答案中删除了这个并改为使用)
SET @timeMinimum='2017-03-17 08:00:00';
SET @timeMaximum='2017-03-17 17:00:00';
SELECT IF (d.name = 'Free', @timeMinimum, b.start_time) AS free_from,
IF (d.name = 'Free', b.start_time, @timeMinimum := b.start_time + INTERVAL b.duration MINUTE) AS free_until,
d.name AS Free
FROM (SELECT 1 AS place, 'Free' AS NAME UNION SELECT 2 AS place, 'Booked' AS NAME ) AS d
INNER JOIN booked_appointments b
HAVING free_from < free_until
UNION SELECT @timeMinimum AS free_from, @timeMaximum AS free_until, 'Free' AS Free
FROM (SELECT 1) AS d
WHERE DATE(@timeMinimum) < DATE(@timeMaximum)
ORDER BY free_from, free_until;
查询几乎所有操作都正确,除了它忽略了我设置的timeMinimum和timeMaximum,而是返回整个表的结果,范围从2017-03-17到2017-03-24。一旦我查询当天的工作,这可能不是问题,但它也忽略了我故意在表中乱序以测试输入数据的真实示例的最后一个测试日期。
以下是上述查询的输出:
+---------------------+---------------------+--------+
| free_from | free_until | Free |
+---------------------+---------------------+--------+
| 2017-03-17 08:00:00 | 2017-03-17 10:45:00 | Free |
| 2017-03-17 10:45:00 | 2017-03-17 11:30:00 | Booked |
| 2017-03-17 11:30:00 | 2017-03-22 09:30:00 | Free |
| 2017-03-22 09:30:00 | 2017-03-22 10:30:00 | Booked |
| 2017-03-22 10:30:00 | 2017-03-24 08:45:00 | Free |
| 2017-03-22 11:30:00 | 2017-03-22 12:30:00 | Booked |
| 2017-03-24 08:45:00 | 2017-03-24 11:30:00 | Booked |
+---------------------+---------------------+--------+
预期输出为:
+---------------------+---------------------+--------+
| free_from | free_until | Free |
+---------------------+---------------------+--------+
| 2017-03-17 08:00:00 | 2017-03-17 10:45:00 | Free |
| 2017-03-17 10:45:00 | 2017-03-17 11:30:00 | Booked |
| 2017-03-17 11:30:00 | 2017-03-17 17:00:00 | Free |
+---------------------+---------------------+--------+