Room Booking Query

前端 未结 2 1509
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 01:29

I have a problem in writing the sql to get the availables rooms from the tables.

My tables structures are given below.

Table Booking
ID | START_DATE         


        
相关标签:
2条回答
  • 2020-12-04 01:45

    You'll want to define a clear recordsets for "all bookings made on day X", and then use an outer join to retrieve those rooms that don't have a booking for said day.

    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
    )
    

    Edit:

    Since you want ALL open rooms during a reservation, you'll need to do a more complicated query. I'll assume that you already have the dates in question loaded outside, since doing a date-based many-to-many query is a 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
    )
    
    0 讨论(0)
  • 2020-12-04 01:52

    If all you want is the list of rooms available for the entire range of desired dates, then something like the following might work:

    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
    

    So, using the original example, we might get:

    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
    
    0 讨论(0)
提交回复
热议问题