查找数据库表中是否有时隙

时间:2012-11-22 13:14:38

标签: mysql database

我有以下数据库表和列。

+----+---------------------+---------------------+------------------+
| id | start_datetime      | end_datetime        | arena_surface_id |
+----+---------------------+---------------------+------------------+
|  1 | 2012-11-22 02:30:00 | 2012-11-22 05:00:00 |                2 |
|  2 | 2012-11-22 00:00:00 | 2012-11-22 02:30:00 |                2 |
|  3 | 2012-11-22 05:00:00 | 2012-11-22 08:00:00 |                2 |
|  4 | 2012-11-22 08:00:00 | 2012-11-22 11:00:00 |                2 |
|  5 | 2012-11-22 11:00:00 | 2012-11-22 17:00:00 |                2 |
+----+---------------------+---------------------+------------------+

用户输入日期,开始时间和结束时间,我想知道在给定的时间段内是否为特定的arena_surface_id预订了任何插槽。

例如,如果用户输入是。

start_datetime : 2012-11-22 6:00
end_datetime : 2012-11-22 9:00
arena_surface_id : 2

我想知道在给定的日期时间是否有任何行与6:00到9:00之间的时段相匹配(在上面的示例中它应该匹配)。

什么是适当的mysql查询?

这实际上是此how would I detect a non-overlap of two time periods?

的后续问题

更新

@March这是我使用你的查询时返回的内容。

SELECT 
    id, 
    start_datetime, 
    end_datetime, 
    arena_surface_id 
FROM 
    gce_arena_surface_booking 
WHERE 
    (start_datetime BETWEEN '2012-11-22 04:00:00' AND '2012-11-22 09:00:00')
OR 
    (end_datetime BETWEEN '2012-11-22 4:00:00' AND '2012-11-22 9:00:00')


+----+---------------------+---------------------+------------------+
| id | start_datetime      | end_datetime        | arena_surface_id |
+----+---------------------+---------------------+------------------+
|  1 | 2012-11-22 02:30:00 | 2012-11-22 05:00:00 |                2 |
|  3 | 2012-11-22 05:00:00 | 2012-11-22 08:00:00 |                2 |
|  4 | 2012-11-22 08:00:00 | 2012-11-22 11:00:00 |                2 |
+----+---------------------+---------------------+------------------+

中间记录与条件不匹配,仍然取出它。

1 个答案:

答案 0 :(得分:7)

怎么样

SELECT * 
FROM yourTable
WHERE (startTime BETWEEN 'yourStartImput' AND 'yourEndImput') OR (endTime BETWEEN 'yourStartImput' AND 'yourEndImput')

所以你检查输入之间是否有匹配开始或结束。

对于您的评论,您的最终查询应如下所示:

SELECT * 
FROM yourTable
WHERE ((startTime BETWEEN 'yourStartImput' AND 'yourEndImput') 
  OR (endTime BETWEEN 'yourStartImput' AND 'yourEndImput')) 
  AND arena_surface_id = 1