I had this database structure in a hotel reservation in terms of room availability
below is my table of room
room_num roomtype
101 Single
102 Single
103 Single
111 Deluxe
112 Deluxe
113 Deluxe
114 Deluxe
115 Deluxe
116 Deluxe
121 Superior
122 Superior
and the table below is room_booked
which is records booked room numbers
dor
is checkin date and dco
is date checkout
room_num dor dco
111 2014-06-01 2014-06-06
112 2014-06-01 2014-06-06
113 2014-06-01 2014-06-06
114 2014-06-01 2014-06-06
115 2014-06-01 2014-06-06
116 2014-06-01 2014-06-06
112 2014-05-18 2014-05-21
113 2014-08-01 2014-08-04
In this case, all of Deluxe room are booked from 2014-06-01
to 2014-06-06
. Then I selected Deluxe room available from 2014-06-01 to 2014-06-06 by using this MySQL code below
SELECT
room.room_num
FROM
room
LEFT JOIN
room_booked ON room_booked.room_num = room.room_num
WHERE
(
(
dor IS NULL AND dco IS NULL
)
OR (
-- wished booking date is before DOR
'2014-06-06' < dor
-- OR wished booking date is after DCO
OR '2014-06-01' >= dco
)
)
-- room type
AND roomtype = 'Deluxe'
However it shows Deluxe room no. 112 and 113 which is booked before and after selected date range above instead of 0 or fully booked. Is there any solution to fix this code?
I think you have to check both dates for check in and check out:
SELECT
room.room_num
FROM
room
WHERE
roomtype = 'Deluxe' AND
room.room_num not in
(
SELECT
room_booked.room_num
FROM
room_booked
WHERE
(room_booked.dor<='2014-06-1' and room_booked.dco>='2014-06-1')
OR
(room_booked.dor<'2014-06-06' and room_booked.dco>='2014-06-06')
OR
(room_booked.dor>='2014-06-01' and room_booked.dco<'2014-06-06')
)
re-Edited answer and created a sqlfiddle for testing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.