表如下
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)
但是,如果在数据库中存储了多个预订房间,就会看到我的数据库问题的结构,即使房间在那个日期范围内不是免费的,它也会预订房间
答案 0 :(得分:1)
请考虑以下图表(对不起笔迹的影响):
在上图中,我们可以在水平轴上看到日期范围。 From_D
至To_D
代表特定房间的预订空位。考虑到四种情况的到达和离开日期(分别以A i 和D i 表示)。
当到达和离开日期完全在预订的位子的左侧或右侧时,我们可以清楚地看到特定房间仅 可用。
我们可以在GROUP BY
上RoomID
,并使用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(*)
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月1日至2018年11月3日之间是否有空
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 |
答案 1 :(得分:0)
在您的日期上使用 BETWEEN 和 AND
SELECT DISTINCT RoomId FROM bookings
WHERE (date_field BETWEEN From_D AND To_d)
答案 2 :(得分:0)
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
答案 3 :(得分:-1)
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))