Reputation: 1668
I am trying to create an online room reservation system.
One of the tables of the database is supposed to hold the bookings. It has an autonumber field, customer data fields, two date fields for arrival and departure, and anther table booking details have: bookedid, roomid and room count.
A search page submits the arrival and departure dates to a result page which is then supposed to tell the customer how many rooms are available within the period if any. This is where it all goes wrong. I just can't get an accurate count of the number of rooms already booked within the period requested.
Bookings table
id|guest | arrive | depart 1 |Smith | 2017-12-20 | 2017-12-25 2 |Jones | 2017-12-21 | 2017-12-25 3 |Brown | 2017-12-23 | 2017-12-27 4 |White | 2017-12-24 | 2017-12-26
Booking Details table
id | booked_id | room_id |room_count 1 | 1 | 1 | 2 2 | 1 | 2 | 2 3 | 2 | 1 | 4 4 | 3 | 2 | 2 5 | 3 | 1 | 2 6 | 4 | 1 | 2
Rooms table - Room room_id
comes from here.
room_id | type | count |amount 1 | Single room | 10 | 1000 2 | Deluxe room | 5 | 2000
I want a particular rooms availability (for eg:room_id is 1)
date available roomid 2017-12-20 | 8 | 1 2017-12-21 | 4 | 1 2017-12-22 | 4 | 1 2017-12-23 | 2 | 1 2017-12-24 | 0 | 1 2017-12-25 | 0 | 1 2017-12-26 | 4 | 1 2017-12-27 | 8 | 1 2017-12-28 | 10 | 1 2017-12-25 | 10 | 1
I am also using calender table. and i have written a query like
SELECT x.dt , r.room_cnt - COALESCE(SUM(d.`booking_cnt`),0) available
FROM calendar_table x
LEFT JOIN bookings y ON x.dt >= y.`date_from` AND x.dt < y.`date_to`
LEFT JOIN booking_details d ON d.booking_id=y.id
LEFT JOIN rooms r ON r.id= 1
WHERE x.dt BETWEEN now() AND now() + interval 3 month GROUP BY dt
But this is not working properly.
Upvotes: 0
Views: 1709
Reputation: 147
Modify the query like this,
SELECT x.dt , r.room_cnt,SUM(d.`booking_cnt`) booked,r.room_cnt- SUM(d.`booking_cnt`) available FROM calendar_table x
LEFT JOIN bookings y ON x.dt >= y.`date_from` AND x.dt < y.`date_to`
LEFT JOIN booking_details d ON d.booking_id=y.id and d.room_id='1'
LEFT JOIN rooms r ON r.id= 1
WHERE x.dt BETWEEN now()-interval 3 month AND now() + interval 3 month GROUP BY dt
Upvotes: 1