在给定的日期范围内选择可用房间

时间:2014-04-28 15:56:53

标签: mysql sql

我正在建立一个酒店预订系统,当我试图查询一个给定范围内的所有可用房间类型时,我就陷入困境。

我有两张表RoomsReservationsRooms桌子占据了酒店的房间。他们的号码(id)及其类型(type)。

Reservations保留客户的预订。预订编号(id),相关联的房间号(room_id)和日期范围(fromto

我试过这个问题:

SELECT room_id as available_room_number, type

FROM roomstesting

LEFT JOIN reservations ON roomstesting.id = reservations.room_id
WHERE reservations.id 
  NOT IN (reservations.e_from <='"2014-03-07 19:00:00' 
           AND reservations.e_to >='2014-03-08 19:00:00')

我试图获取3月7日到3月8日范围内所有可用的房间类型。我希望得到modern room作为查询的结果。因为modern room id 4没有与日期范围重叠的保留,所有其他3个房间都有3月6日到3月9日的预订。但我没有得到我想要的结果。以下是我的数据库结构(简化)

房间

| id | type         |
|||||||||||||||||||||
|  1 | master suite |
|  2 | master suite |
|  3 | modern room  |
|  4 | modern room  |

预订

| id | room_id | from                | to                  |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|  1 |    1    | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 |
|  2 |    2    | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 |
|  3 |    3    | 2014-03-05 08:00:00 | 2014-03-09 08:00:00 |

预期结果

| available_room_number | type       |
||||||||||||||||||||||||||||||||||||||
|          4            | modern room|

如果有人在这里可以告诉我如何处理这个问题,那将是完美的。期待您的回复。

4 个答案:

答案 0 :(得分:1)

为什么不反转比较符号

WHERE reservations.e_from&gt;'2014-03-07 19:00:00'            和reservations.e_to&lt;'2014-03-08 19:00:00'

答案 1 :(得分:1)

试试这个:

SELECT * FROM Rooms WHERE ID NOT IN(SELECT room_id FROM reservations WHERE '2014-03-07 19:00:00' < e_to AND '2014-03-08 19:00:00' > e_from)

答案 2 :(得分:1)

4号房间没有预订,因此JOIN没有接听。尝试这样的事情:

SELECT    room_id, type
FROM      roomstesting
WHERE     room_id NOT IN (
             SELECT    reservations.room_id
             FROM      reservations
             WHERE     (
                          reservations.e_from <= '2014-03-07 19:00:00' AND
                          reservations.e_to >= '2014-03-08 19:00:00'
                       ) OR (
                          reservations.e_from <= '2014-03-07 19:00:00' AND
                          reservations.e_to < '2014-03-08 19:00:00'
                       ) OR
                       (
                          reservations.e_from > '2014-03-07 19:00:00' AND
                          reservations.e_to >= '2014-03-08 19:00:00'
                       ) OR
                       (
                          reservations.e_from > '2014-03-07 19:00:00' AND
                          reservations.e_to < '2014-03-08 19:00:00'
                       )
                       )

答案 3 :(得分:0)

我总是尝试使用BETWEEN,它可以正常工作

select * from roomstesting 
where room_id not in
(select room_id from roomstesting where date between begin_date and end_date)