Sql 在日期范围内搜索日期
Sql search date between range of dates
我在数据库中有两个表
房间:包含房间的详细信息
booking:包含有关房间的预订信息
房间:
+----+----------+---------------+---------+
| 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 号房间
检查重叠时段的通常逻辑是: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'
);
我在数据库中有两个表
房间:包含房间的详细信息
booking:包含有关房间的预订信息
房间:
+----+----------+---------------+---------+
| 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 号房间
检查重叠时段的通常逻辑是: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'
);