mysql - 如何从可用时段和预订时段中查找空闲时段

标签 mysql

我有两张表,一张是可用时间段,另一张是预订时间段,其中包含开始日期时间和结束日期时间。我想退回空闲时间段。

表1

available_slots
start_datetime      |end_datetime
-----------------------------------------
2020-01-14 05:00:00 |2020-01-14 06:00:00
-----------------------------------------
2020-01-14 06:00:00 |2020-01-14 07:00:00
-----------------------------------------
2020-01-14 07:00:00 |2020-01-14 08:00:00
-----------------------------------------
2020-01-14 08:00:00 |2020-01-14 09:00:00
-----------------------------------------
2020-01-14 09:00:00 |2020-01-14 10:00:00
-----------------------------------------
2020-01-14 10:00:00 |2020-01-14 11:00:00
-----------------------------------------
2020-01-14 11:00:00 |2020-01-14 12:00:00
-----------------------------------------
2020-01-14 12:00:00 |2020-01-14 13:00:00
-----------------------------------------
2020-01-14 13:00:00 |2020-01-14 14:00:00
-----------------------------------------
2020-01-14 14:00:00 |2020-01-14 15:00:00
-----------------------------------------
2020-01-14 15:00:00 |2020-01-14 16:00:00
-----------------------------------------
2020-01-14 16:00:00 |2020-01-14 17:00:00

表2

booked_slots
start_datetime      |end_datetime
-----------------------------------------
2020-01-14 07:00:00 |2020-01-14 08:00:00
-----------------------------------------
2020-01-14 13:00:00 |2020-01-14 14:15:00
-----------------------------------------

结果应该是

Free slots
start_datetime      |end_datetime
-----------------------------------------
2020-01-14 05:00:00 |2020-01-14 06:00:00
-----------------------------------------
2020-01-14 06:00:00 |2020-01-14 07:00:00
-----------------------------------------
2020-01-14 08:00:00 |2020-01-14 09:00:00
-----------------------------------------
2020-01-14 09:00:00 |2020-01-14 10:00:00
-----------------------------------------
2020-01-14 10:00:00 |2020-01-14 11:00:00
-----------------------------------------
2020-01-14 11:00:00 |2020-01-14 12:00:00
-----------------------------------------
2020-01-14 12:00:00 |2020-01-14 13:00:00
-----------------------------------------
2020-01-14 15:00:00 |2020-01-14 16:00:00
-----------------------------------------
2020-01-14 16:00:00 |2020-01-14 17:00:00

最佳答案

SELECT table1.*
FROM table1 
WHERE NOT EXISTS (SELECT 1 
                  FROM table2  
                  WHERE table2.start_datetime = table1.start_datetime 
                  AND table2.end_datetime = table1.end_datetime);

关于mysql - 如何从可用时段和预订时段中查找空闲时段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764380/

相关文章:

php - 如何获取两个或多个表中的同一列?

java - 在 Spring Batch 3.0.x 中 - 如何为非标准数据库设置数据库类型?

MYSQL 按日期格式排序 "06:21, 28 February 2014"

mysql - 恢复特定表中的数据

MySQL 同一列在 2 个不同日期之间的最大差异

mysql - 将具有两个 FK 列的 ORM 推向同一个外部表

c# - 在新连接中提交事务

sql - 尝试使用条件中的变量进行查询时出现问题(存储过程)

mysql select sum, max, and another column value at the same row which the max value 停留

php - 此 PDO 准备语句返回 false 但不会引发错误