Reputation: 13206
Hi everyone I am in the process of building a room allocating system that checks if a room is available on a given date. There are about 20 unique room ids and I've just included as snippet of several above.
So for example if the user types in the date of 2012-01-01 I would want the room_id of 1 to be excluded from the results because as seen above it has been already booked for that date.
In a sense any match found between the user's in-putted date should cause the entire list of corresponding room_id's to be excluded from the list.
I used the below SQL query:
SELECT DISTINCT room_id
FROM room_booking
WHERE date_booked<>'$date'
Unfortunately it doesn't work because although it excludes the result for a single row, it includes the rest of the results for a given room_id?
Upvotes: 5
Views: 68618
Reputation: 196
The above should work however may potentially become slow if a lot of rooms are added. You may want to consider a left outer join. It will typically be faster as the above will be performing sub queries i.e. For every room, requery the database to check if it has a value of this date which results in 40 * 40 checks each time this query is executed and will increase with the number of current bookings.
The below should be more efficient and should be valid on quite a few database platforms. Of course, this depends on how much the count of values may change if there are any string performance related items to consider...
SELECT DISTINCT room_id
FROM room_booking rb1
LEFT OUTER JOIN room_booking datecheck
ON rb1.room_id = datecheck.room_id
AND datecheck.date_booked = @date
WHERE datecheck.room_id is null
Upvotes: 2
Reputation: 30651
Considering you have a column called RoomID
I'm going to assume that there is a Room table with a corresponding column RoomID - this is probably a much better place to look for all rooms as you can't guarantee every room has a booking, and so can't rely on the booking table alone.
Then you can look up with a sub-query which rooms are booked on a date, then return all the RoomIds which aren't in that list.
select RoomID from Room
where RoomID not in
(select RoomID from room_booking
where date = @date)
Upvotes: 3
Reputation: 6817
Not tried this, but here goes
SELECT DISTINCT room_id
FROM room_booking
WHERE room_id NOT IN
(SELECT DISTINCT room_id
FROM room_booking
WHERE date_booked = '$date'
)
Upvotes: 11
Reputation: 231661
You could use a NOT EXISTS
SELECT DISTINCT room_id
FROM room_booking rb1
WHERE NOT EXISTS( SELECT 1
FROM room_booking rb2
WHERE rb2.date_booked = <<date>>
AND rb2.room_id = rb1.room_id )
or a NOT IN
SELECT DISTINCT room_id
FROM room_booking
WHERE room_id NOT IN (SELECT room_id
FROM room_booking rb2
WHERE rb2.date_booked = <<date>>)
Upvotes: 11