这些天我正努力学习酒店客房预订系统的学位课程。
现在我开始检查可用性阶段。
这是我的表结构
预订
`ID` int(11)
`roomID` int(11)
`startDate` date
`endDate` date
客房表
`roomID` int(11)
`name` varchar(255)
`facilities` mediumtext
想象一下有5个房间。 roomIDs是01,02,03,04和05。
在这些房间,01预订。签到日期是05-11-2013&结帐日期是10-11-2013。
还有roomID 04,预订于2013年11月8日至2013年11月9日期间
如果用户检查从04-11-2013到10-11-2013的可用性,则仅显示房间ID 02,03和05。
如何建立一个显示结果的系统?
有人可以帮我构建SQL查询来检查可用性吗?
答案 0 :(得分:1)
逻辑在这里实际上非常简单,你不需要任何开始和结束都在你的时期内的东西,或者它们在你正在寻找的范围内的任何一点的相对侧。
SELECT
R.roomID,
R.name,
R.facilities
FROM
-- Use the table rooms, but name it R for shorthand.
Rooms R
-- Left joins return null if there's no match, which we use in the where clause to identify these rows
LEFT JOIN Bookings B
-- B is bookings, R is rooms, they're aliased to make things easier
ON B.RoomId = R.RoomId
AND
(
-- As I said at the top of this answer, we want to exclude anything that matches any of 3 conditions:
-- The start date is between the date's the room is already booked for
@SearchCheckingStart BETWEEN B.startDate AND B.endDate
OR
-- The end date is in the period where the room is already booked
@SearchCheckingEnd BETWEEN B.startDate AND B.endDate
OR
-- Or our date range lies between the period we're booking for
B.startDate BETWEEN @SearchCheckingStart AND @SearchCheckingEnd
)
WHERE -- We're only interested in results where MySQL couldn't match the results earlier, this gives us the rooms that are free.
B.RoomId IS NULL