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

标签 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|

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

最佳答案

试试这个:

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)

关于mysql - 选择给定日期范围内的可用房间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23345723/

相关文章:

mysql - 子查询在 MySQL 过程中返回多于 1 行

c# - 为不同的数据库转换 SQL 查询

mysql - OUTFILE MySQL 不能与联合一起工作

php - 存储查询结果并在另一个查询中使用

mysql - 带有 INNER JOIN 的 SQL DELETE

php - 如果值匹配则更新行,否则插入新行

sql - 数据透视问题,SQL Server

mysql - 需要从 MySQL 中获取行

PHP/MySQL : how to dynamically change my (large and always changing) database

mysql - 如何优化此 VIEW 语句?