订房查询

我在编写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'

)

回答:

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

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

以上是 订房查询 的全部内容, 来源链接: utcz.com/qa/407534.html

回到顶部