【问题标题】:Select specific records between two dateranges选择两个日期范围之间的特定记录
【发布时间】:2017-02-03 02:23:55
【问题描述】:

我正在尝试根据用户提供的日期范围获取未预订的酒店房间。

我有两张桌子

  • 房间,列有room_id、roomno
  • reservations 列reserv_id、room_id、checkindate、checkoutdate

我正在应用这个查询

$sql = "SELECT DISTINCT roomno 
FROM rooms 
LEFT JOIN reservation ON rooms.room_id = reservation.room_id 
AND 
(
    (
        (reservation.checkindate > '$newreservcheckin') 
        AND
        (reservation.checkindate > '$newreservcheckout')
    ) 
    OR 
    (
        (reservation.checkoutdate < '$newreservcheckin') 
        AND 
        (reservation.checkoutdate < '$newreservcheckout')
    )
)";

$newreservcheckin$newreservcheckout 是用户提供的日期范围

假设我们有房间号为 100 和 101 的房间 现在从 9-16-2016 到 9-18-2016 预订了 100 个 从 2016 年 9 月 27 日到 2016 年 9 月 29 日,还有 100 人被预订 并且101房间是未预订的(意味着它在预订表中没有记录)

假设如果用户给出日期 9-26-2016 到 9-30-2016 查询将忽略从 9-27-2016 到 9-29-2016 的房间号 100 条目,但会显示房间号 100 的日期从 9-16-2016 到 9-18-2016,将显示 101 个房间

如何塑造查询,使其不会给出相同的房间,而是给出不同日期的房间?

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您需要选择 (A) 未预订或 (B) 已预订但超出您查询范围的房间,以下查询应该有效:

    select no from room r
    where not exists (
      select id from reservation where room_id = r.id)
    
    union
    
    select no from room r
    where r.id not in (
      select distinct room_id from reservation
      where 
            checkindate between '2016-09-20' and '2016-09-22'
        OR 
            checkoutdate between '2016-09-20' and '2016-09-22'
    )
    

    这里是SQL Fiddle

    【讨论】:

      【解决方案2】:

      您可以加入与新入住日期重叠的所有预订,并选择没有可加入的房间。在我的查询中,我希望新客人可以在以前结帐的同一日期登记入住。如果不是 - 将“”更改为“>=”。

      SELECT 
          r.roomno
      FROM
          rooms r
              LEFT JOIN
          reservations res ON res.room_id = r.room_id
              AND res.checkindate < '$newreservcheckout'
              AND res.checkoutdate > '$newreservcheckin'
      WHERE res.reserv_id IS NULL
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 2016-09-14
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        相关资源
        最近更新 更多