用于查找从日期x到日期y的可用房间的SQL查询

时间:2013-03-18 20:12:07

标签: sql oracle

在以下关系模式中,如何从DATE RANGE中获取未预订的可用“基本”类型的房间。这是我的镜头。我正在使用sqlplus中的oracle

SELECT * 
    FROM ROOM r, BOOKING b
    WHERE NOT EXISTS
        (SELECT * FROM BOOKINGROOM br
         WHERE br.ROOMNO = r.ROOMNO 
         AND   br.BOOKINGID = b.BOOKINGID
         AND ARRIVEDATE < '01-FEB-2013'
         AND DEPARTDATE > '23-FEB-2013');

我还希望查询为“固定查询”,因此我手动添加结束范围和开始范围日期。子查询答案将是首选。

INSERT INTO BOOKING VALUES (2314, 1001, TO_DATE('10-MAR-2013', 'DD-MON-YYYY'), TO_DATE('15-MAR-2013', 'DD-MON-YYYY'), 1225.00); 

日期比较可能是以下答案中的一个问题。

2 个答案:

答案 0 :(得分:2)

最简单的方法是:

SELECT DISTINCT r.* 
FROM Room r
LEFT JOIN BookingRoom br ON r.FloorNo = br.FloorNo AND r.RoomNo = br.RoomNo
LEFT JOIN Booking b ON br.BookingId = b.BookingId 
      AND (b.ArriveDate <= &end_range AND b.DepartDate >= &start_range)
WHERE b.BookingId IS NULL
  AND r.Type = 'BASIC';

如果您绝对必须使用子查询,请尝试:

SELECT DISTINCT r.* 
FROM Room r
LEFT JOIN BookingRoom br ON r.FloorNo = br.FloorNo AND r.RoomNo = br.RoomNo
LEFT JOIN Booking b ON br.BookingId = b.BookingId 
WHERE (b.BookingId IS NULL OR b.BookingId NOT IN (
      SELECT BookingId 
      FROM Booking
      WHERE (ArriveDate <= &end_range AND DepartDate >= &start_range)
)) AND r.Type = 'BASIC';

答案 1 :(得分:1)

尝试此查询,该查询将检测冲突的预订,无论它们是否包含,包含或部分与所需的日期范围重叠。

SELECT DISTINCT r.* 
FROM Room r
LEFT JOIN BookingRoom br ON r.FloorNo = br.FloorNo AND r.RoomNo = br.RoomNo
LEFT JOIN Booking b ON br.BookingId = b.BookingId 
AND b.ArriveDate < &end_range AND b.DepartDate > &start_range 
WHERE b.BookingId IS NULL
AND r.Type = 'BASIC';