一尘不染

订房查询

mysql

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

我的表结构如下。

Table Booking
ID | START_DATE | END_DATE


Table BookingRoom (Intermediate Table)
ID   | BOOKING_ID   |ROOM_ID

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

Table Room
Contains the ID room

我已经尝试过了,但是如果一个房间在两个不同的日期链接到两个不同的预订会比较麻烦,那么只有第一个预订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,以便在入住和退房之间获得可用的房间。


阅读 393

收藏
2020-05-17

共1个答案

一尘不染

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

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
2020-05-17