mysql查询,查找给定日期“从”和“到”的可用房间

niwlg2el  于 2021-06-19  发布在  Mysql
关注(0)|答案(4)|浏览(279)

表格如下

rooms(RoomId(PK)(int),
      RoomName(varchar))

bookings(RoomId(FK)(int),
         From_D(date),
         To_D(date),
         Bookee(varchar))

(PK-primary Key ,FK-foreign Key)

鉴于 arrival(From_D) 以及 departure(To_D) 日期如何找到可用房间的id
我试过:

SELECT DISTINCT RoomId 
FROM bookings 
WHERE  arrival not in(From_D,To_d) AND 
       departure not in(From_D,To_d)

但是,如果数据库中存储了多个房间的预订,并且即使在该日期范围内房间不是免费的,它也会预订房间,那么就会出现我的数据库结构问题

46qrfjad

46qrfjad1#

请看下面的图表(很抱歉字迹不好):

在上图中,我们可以看到横轴上的日期范围。 From_DTo_D 表示特定房间的已预订插槽。到达和离开日期考虑了四种情况(由ai和di表示)。
我们可以清楚地看到,只有当到达和离开日期完全在预定位置的左侧或右侧时,特定的房间才可用。
我们可以 GROUP BYRoomID 并且只考虑那些房间,每个房间的预订都遵循上面定义的标准,使用 HAVING 条款。
查询将简单地如下所示:

SELECT RoomID 
FROM bookings 
GROUP BY RoomID 
HAVING 
  SUM((From_D < :arrival AND To_D < :arrival) 
             OR 
      (From_D > :departure AND To_D > :departure)) = COUNT(*)

db小提琴演示

CREATE TABLE `rooms` (
 `RoomId` int(4) NOT NULL,
 `RoomName` varchar(20) DEFAULT NULL,
 PRIMARY KEY (`RoomId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `bookings` (
 `RoomId` int(4) NOT NULL,
 `From_D` date NOT NULL,
 `To_d` date NOT NULL,
 `B_Name` varchar(20) NOT NULL,
 KEY `RoomId` (`RoomId`),
 CONSTRAINT `bookings_ibfk_1` FOREIGN KEY (`RoomId`) REFERENCES `rooms` (`RoomId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `rooms` (`RoomId`, `RoomName`) VALUES 
('1', 'Auditorium'), 
('2', 'Room2'), 
('3', 'Room3'), 
('4', 'Room4'), 
('5', 'Room5');

INSERT INTO `bookings` (`RoomId`, `From_D`, `To_d`, `B_Name`) VALUES 
('1', '2018-11-01', '2018-11-03', 'Trance'), 
('2', '2018-11-02', '2018-11-07', 'Alcoding'), 
('3', '2018-11-01', '2018-11-04', 'DebSoc'), 
('4', '2018-11-12', '2018-11-17', 'MunSoc'), 
('5', '2018-11-03', '2018-11-06', 'Pulse');

查询:查看2018-11-01和2018-11-03之间的可用性

SELECT RoomId 
FROM bookings 
GROUP BY RoomID 
HAVING 
  SUM((From_D < '2018-11-01' AND To_D < '2018-11-01') 
             OR 
      (From_D > '2018-11-03' AND To_D > '2018-11-03')) = COUNT(*)

结果:根据样本数据,只有roomid 4可用

| RoomId |
| ------ |
| 4      |
00jrzges

00jrzges2#

在和约会对象之间使用

SELECT DISTINCT RoomId FROM bookings    
WHERE (date_field BETWEEN From_D AND To_d)
x8goxv8g

x8goxv8g3#

Try this :
    SELECT * FROM   rooms room1
    WHERE  NOT EXISTS (SELECT *
                FROM   booking booking1
                       WHERE  room1.roomid = booking1.roomid AND
                              (:from_d BETWEEN booking1.from_d AND booking1.to_d OR
                               :to_d   BETWEEN booking1.from_d AND booking1.to_d))
brccelvz

brccelvz4#

select distinct r.*
from rooms r
    left join bookings b on b.RoomId=r.RoomId
where b.RoomId is null or @arrival > To_D or @departure < from_td

相关问题