简体   繁体   English

房间可用性检查的 SQL 查询

[英]SQL query for room availability check

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.它有一个自动编号字段、客户数据字段、两个用于到达和离开的日期字段,并且花药表预订详细信息有:bookedid、roomid 和房间计数。

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来自这里。

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)我想要一个特定的房间可用性(例如:room_id 是 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.但这不能正常工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM