对于预订系统,我有一张房间,抵达和离开的桌子。
示例数据:
id | room | arrival | departure
---+------+------------+-----------
1 | 1 | 2011-03-12 | 2011-03-14
2 | 1 | 2011-03-08 | 2011-03-09
3 | 1 | 2011-03-19 | 2011-03-20
4 | 2 | 2011-03-22 | 2011-03-30
5 | 2 | 2011-03-19 | 2011-03-22
我现在的问题是:如果我有新的预订(2011-03-10
到2011-03-12
),我该如何查看哪些房间免费?
此示例的输出应为空间1
和2
。
答案 0 :(得分:4)
这是一个查询,它将显示日期范围的非免费房间:
select room from bookings where
(arrival<'2011-03-12' and departure>='2011-03-12') -- overlap at the end
OR (arrival<='2011-03-10' and departure>'2011-03-10') -- overlap at the start
OR (arrival>='2011-03-10' and departure<='2011-03-12') -- complete overlap
您可以将其与
一起使用select roomnumber from rooms where roomnumber not in (... as above ...)
找到免费房间
答案 1 :(得分:1)
您也可以使用BETWEEN
比较运算符来实现此目的。在这种情况下,你会做这样的事情:
SELECT r.id FROM room r WHERE r.id NOT IN
(
SELECT rb.room FROM room_booking rb WHERE
('2011-03-10' BETWEEN rb.arrival AND rb.departure) OR
('2011-03-12' BETWEEN rb.arrival AND rb.departure)
)