1

我有这个带有以下记录的 mysql 表。

表名:gce_arena_surface_booking

+----+---------------------+---------------------+------------------+
| 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 |
|  6 | 2012-11-22 17:30:00 | 2012-11-22 22:00:00 |                2 |
|  7 | 2012-11-23 02:00:00 | 2012-11-23 18:00:00 |                2 |
+----+---------------------+---------------------+------------------+

我需要知道给定的日期时间,如果已经存在任何预订,我正在使用此查询来检查给定的任何预订是否存在start_datetime,并且end_datetime

SELECT 
    id, start_datetime, end_datetime, arena_surface_id 
FROM 
    gce_arena_surface_booking 
WHERE (
    (start_datetime BETWEEN '2012-11-23 2:00' AND '2012-11-23 6:00') OR 
    (end_datetime BETWEEN '2012-11-23 2:00' AND '2012-11-23 6:00')
) 
AND arena_surface_id = 2

上面的查询给我带来了问题,例如,如果我的值从:

'2012-11-23 2:00' AND '2012-11-23 6:00'

'2012-11-23 2:30' AND '2012-11-23 6:00'

请注意,我已将值从 更改2:002:30,如果我这样做,它不会返回任何结果,而参考上面的记录,我希望它返回带有 id 的行,7因为我在2:00and 和之间预订了时间段18:00,因此任何与时间相匹配的给定值02:0018:00应该返回一行。

处理我的问题的正确 mysql 查询是什么?

如果您想使用记录和模式,这里是sqlfiddle的链接。

4

3 回答 3

3

下面给出了查找重叠预订的查询。只需要再添加一项检查来查找我们正在搜索的插槽是否在数据库中已预订的插槽中。它就像搜索槽的开始日期和结束日期都在已经预订的槽中。

SELECT 
    id, start_datetime, end_datetime, arena_surface_id 
FROM 
    gce_arena_surface_booking 
WHERE (
    (start_datetime BETWEEN '2012-11-23 2:30' AND '2012-11-23 6:00') OR 
    (end_datetime BETWEEN '2012-11-23 2:30' AND '2012-11-23 6:00')

  OR '2012-11-23 2:30' BETWEEN start_datetime AND end_datetime


) 
AND arena_surface_id = 2

如果需要找出数据库中不重叠的插槽,请使用以下查询。是对上述的否定。

SELECT * FROM `gce_arena_surface_booking`
WHERE (`arena_surface_id`=2)
AND
(start_datetime NOT BETWEEN '2012-11-23 02:30:00' AND '2012-11-23 06:00:00')
AND
(end_datetime NOT BETWEEN '2012-11-23 02:30:00' AND '2012-11-23 06:00:00')
AND
('2012-11-23 02:30:00' NOT BETWEEN start_datetime AND end_datetime)
于 2012-11-26T05:40:49.830 回答
1
   SELECT 
        id, start_datetime, end_datetime, arena_surface_id 
    FROM 
        gce_arena_surface_booking 

    Where ('2012-11-23 2:30' between start_datetime and end_datetime)
    and ('2012-11-23 6:00' between start_datetime and end_datetime)
于 2012-11-23T10:36:04.207 回答
1

在新预订结束时或之后开始的预订,或者在新预订开始时或之前结束的预订都没有问题。

因此,您需要查找的预订​​既在您的新预订结束之前开始,又在您的新预订开始之后结束。

你的查询应该是

SELECT id, start_datetime, end_datetime, arena_surface_id 
FROM gce_arena_surface_booking 
WHERE ('2012-11-23 6:00' > start_datetime)
AND ('2012-11-23 2:00' < end_datetime)
AND arena_surface_id = 2
于 2012-11-23T11:28:37.827 回答