SQL查询可预订的房间
我一直在尝试创建一个查询来检查两个日期之间的可用房间,但迄今为止没有成功。请查找用于创建下表的sql代码。我真的需要你的帮助。这样做是因为系统希望我添加更多细节SQL查询可预订的房间,sql,oracle,date,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 r
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表的两行。非常感谢您的帮助。您可以从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设置;相反,您可以使用date LITERALS,它是ANSI SQL标准的一部分,Oracle支持它,如date'yyyy-mm-dd'。不要将日期存储为varchar。将其存储为Date您在bookings\u roombookings中插入320,但它在rooms表中不存在。是的,数据比我最初插入的要多