I think the best way to do this is to simply run a query to see if a room is occupied and indicate availability in the event that no rows are returned.
As such, for you first query:
SELECT COUNT(id) AS occupied_days FROM availability
WHERE room_id = 123
AND date_occupied BETWEEN @start_date AND @end_date;
If occupied_days == 0
then the room is available.
For your second query, just replace @end_date
with DATE_ADD(@start_date, @num_days)
Just some comments on answers involving a join: since you're limiting your search to a specific room_id
, it makes no sense to join the availability
table to the room
table, since it's providing no necessary information. All these LEFT JOIN
s are just complicating the query, potentially impairing performance and providing nothing of any use.
Also, while you may baulk at the approach of searching for occupancy and then inferring availability, I would guess that this query is by far the fastest and easiest for the query engine to optimize, since it's based on a single column which, if indexed, will make things even faster.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…