我在数据库中有两个表
房间:包含房间的详细信息
预订:包含有关房间的预订信息
房间:
+----+----------+---------------+---------+
| id | hotel_id | room_category | room_no |
+----+----------+---------------+---------+
| 1 | 1 | delux | 1 |
| 2 | 1 | delux | 2 |
| 3 | 1 | delux | 3 |
| 4 | 1 | delux | 4 |
| 5 | 1 | delux | 5 |
+----+----------+---------------+---------+
预定:
+----+------------+----------+---------------+--------------+---------------+---------+----------------+
| id | booking_id | hotel_id | room_category | checkin_date | checkout_date | room_no | booking_status |
+----+------------+----------+---------------+--------------+---------------+---------+----------------+
| 1 | 1 | 1 | delux | 2016-08-25 | 2016-08-30 | 1 | y |
| 2 | 2 | 1 | delux | 2016-08-25 | 2016-08-28 | 2 | y |
+----+------------+----------+---------------+--------------+---------------+---------+----------------+
现在我写一个查询:
select * from rooms
where
hotel_id =1 and
room_category="delux"
and id not in(
select room_no
from bookings
where
checkin_date between '2016-08-25' and '2016-08-28'
or
checkout_date between '2016-08-25' and '2016-08-28'
);
问题: 1.从26-27结果搜索可用性时,包含1号和2号房间
答案 0 :(得分:3)
检查重叠时段的通常逻辑是:begin_1 < end_2 and end_1 >= begin_2
因为酒店房间可以在前一个预订结束的同一天预订。
select * from rooms
where hotel_id =1
and room_category="delux"
and id not in
(
select room_no
from bookings
where checkin_date < '2016-08-28'
and checkout_date >= '2016-08-25'
);