0

我在编写 sql 以从表中获取可用房间时遇到问题。

我的表格结构如下所示。

Table Booking
ID | START_DATE | END_DATE


Table BookingRoom (Intermediate Table)
ID   | BOOKING_ID   |ROOM_ID

一个房间可以链接到多个预订,一个预订可以包含多个房间

Table Room
Contains the ID room

我已经尝试过了,但是如果一个房间在不同的日期与 2 个不同的预订相关联,那么将仅使用第一个预订 ID 进行比较

SELECT DISTINCT r.ID FROM room AS r ,booking AS b,bookingroom AS br
 WHERE r.ID = br.ID_ROOM
 AND b.ID = br.ID_BOOKING
 AND (
           b.END_DATE < '05/14/2013'
        OR b.START_DATE > '05/15/2013'
     )

有人可以帮我编写 SQL 以获取入住和退房日期之间的可用房间。

4

2 回答 2

2

如果您想要的只是整个所需日期范围内的可用房间列表,那么类似以下的内容可能会起作用:

Select Room.Id
From Room
Where Room.Id Not In    (
                        Select RoomId
                        From BookingRoom
                            Join Booking
                                On Booking.Id = BookingRoom.BookingId
                        Where Booking.StartDate <= 'DesiredEndDate'
                            And Booking.EndDate >= 'DesiredStartDate'
                        )
Order By Room.Id

因此,使用原始示例,我们可能会得到:

Select Room.Id
From Room
Where Room.Id Not In    (
                        Select RoomId
                        From BookingRoom
                            Join Booking
                                On Booking.Id = BookingRoom.BookingId
                        Where Booking.StartDate <= '2013-05-15'
                            And Booking.EndDate >= '2013-05-14'
                        )
Order By Room.Id
于 2013-05-15T01:16:36.833 回答
0

您需要为“在第 X 天进行的所有预订”定义一个清晰的记录集,然后使用外部连接来检索那些在当天没有预订的房间。

SET @myDate = #someDay#
SELECT R.ID
FROM Room R
WHERE R.ID NOT IN (
    SELECT BR.ROOM_ID
    FROM BookingRoom BR
    INNER JOIN Booking B ON BR.Booking_ID = B.ID
    WHERE @myDate BETWEEN B.start_date and B.end_date
)

编辑:

由于您希望在预订期间拥有所有打开的房间,因此您需要进行更复杂的查询。我假设您已经在外部加载了相关日期,因为执行基于日期的多对多查询是一个 PITA。

SET @dateStart = #Start#
SET @dateEnd = #End#

SELECT R.ID
FROM Room R
WHERE R.ID NOT IN (
    SELECT BR.ROOM_ID
    FROM BookingRoom BR
    INNER JOIN Booking B ON BR.Booking_ID = B.ID
    WHERE B.start_date BETWEEN @dateStart AND @dateEnd
    AND B.end_date BETWEEN @dateStart AND @dateEnd
)
于 2013-05-15T00:05:25.390 回答