find if time slots are available in database table

2020-07-24 03:48发布

问题:

i have the following database table with columns.

+----+---------------------+---------------------+------------------+
| 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 |
+----+---------------------+---------------------+------------------+

with the user input of date, start time, and end time, i want to find out if there are any slots booked for particular arena_surface_id within the given period of time.

for example if user input is.

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

i want to know if there are any rows which matches time slot between 6:00 and 9:00 for the given date time (in the above example it should match).

what would be the proper mysql query for this?

This is actually a follow up question for this how would I detect a non-overlap of two time periods?

UPDATE

@March this is what it returns when i use your query.

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 |
+----+---------------------+---------------------+------------------+

the middle record does not match the condition, and still fetches it.

回答1:

How about

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

So you check if there's a match that starts or ends between your input.

For your comment, your final query should look like this:

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