SQL查询可预订的房间

时间:2019-12-06 22:17:46

标签: sql oracle date

我一直在尝试创建一个查询以检查两个日期之间的可用房间,但是到目前为止还没有成功。请找到用于创建下表的sql代码。我真的很需要您的帮助。这样做是因为系统要我添加更多详细信息

CREATE TABLE rooms (
    id   NUMERIC(3) NOT NULL,
    type VARCHAR2(11) NOT NULL,
    CONSTRAINT pk_rooms PRIMARY KEY (id),
    CONSTRAINT fk_type
    );

INSERT INTO rooms VALUES (101, 'Excellent');
INSERT INTO rooms VALUES (102, 'Excellent');
INSERT INTO rooms VALUES (103, 'Excellent');
INSERT INTO rooms VALUES (104, 'Excellent');
INSERT INTO rooms VALUES (105, 'Excellent');
INSERT INTO rooms VALUES (106, 'Excellent');
INSERT INTO rooms VALUES (107, 'Excellent');
INSERT INTO rooms VALUES (108, 'Excellent');
INSERT INTO rooms VALUES (109, 'Excellent');
INSERT INTO rooms VALUES (110, 'Excellent');
INSERT INTO rooms VALUES (111, 'Excellent');
INSERT INTO rooms VALUES (112, 'Excellent');

CREATE TABLE bookings_roombookings (
book_id  VARCHAR(20) NOT NULL, 
room_id  NUMBER NOT NULL,  
fromdate DATE NOT NULL, 
todate   DATE NOT NULL, 
guest1   VARCHAR(40) NOT NULL, 
guest2   VARCHAR(40), 
guest3   VARCHAR(40), 
CONSTRAINT cpk PRIMARY KEY (book_id, room_id),  
CONSTRAINT fk_rid FOREIGN KEY (room_id) REFERENCES rooms(id));

INSERT INTO bookings_roombookings VALUES ( 
'DTR5000000', 320, 
'01-JUN-2020', '01-SEP-2020', 
'D.Trump', 'H.Clinton', 'S.Daniels');

INSERT INTO bookings_roombookings VALUES ( 
'DRI0000002', 102, 
'11-DEC-19', '01-SEP-20', 
'D.Ridley', NULL, NULL);

我的查询如下:

select r.id from rooms r
where  r.id not in
       ( select bkr.room_id from bookings_roombookings bkr
         where  (fromdate > '15-JUN-20') and (todate < '18-JUN-20') );

但是这将返回bkr表的两行。我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以从room表开始,并在相关子查询中使用not exists条件,以消除预订时间与目标日期范围重叠的房间:

select r.* 
from rooms r 
where not exists (
    select 1
    from bookings_roombookings bkr
    where 
        bkr.room_id = r.id
        and bkr.fromdate <= date'2020-06-15'
        and bkr.todate >= date'2020-06-18'
)

注意:不要依赖于从字符串到日期的隐式转换(如fromdate > '15-JUN-20'),这取决于数据库和会话的nls设置;相反,您可以使用日期文本,它们是ANSI SQL标准的一部分,并且受Oracle支持,例如date'yyyy-mm-dd'