2017-10-14 96 views
0

我在SQL Server中建立了一個酒店預訂數據庫。表中的三個是如下:SQL太複雜的嵌套查詢 - 你能簡化一下嗎?

E-model

相關列的表中有:

  • BookingBookingID(PK),CheckInDateCheckoutDate
  • RoomBookingRoomBookingID(PK), FK_Booking_ID(FK),FK_RoomID(FK)
  • RoomRoomID(PK)

現在我寫了一個SQL查詢(如下所示),試圖找出在某個日期(2017-10-02到2017-10-04)哪些房間是免費的。代碼解決了這個問題,但變得非常複雜。我知道如何通過在表RoomBooking中使CheckInDateCheckOutDate更容易地解決這個問題,但我希望此設置能夠正常工作。你有什麼想法如何簡化下面的代碼?

BR /麥克

SELECT FK_RoomID 
FROM RoomBooking 
WHERE FK_RoomID IN 
     (SELECT FK_RoomID 
     FROM RoomBooking 
     WHERE FK_BookingID NOT IN  
      (SELECT BookingID 
       FROM Booking 
       WHERE CheckInDate <= '2017-10-04' 
       AND CheckOutDatum > '2017-10-02') 
      ) 
     AND FK_RoomID NOT IN 
      (SELECT FK_RoomID 
       FROM RoomBooking 
       WHERE FK_BookingID IN  
        (SELECT FK_BookingID 
        FROM RoomBooking 
        WHERE FK_RoomID IN  
          (SELECT FK_RoomID 
          FROM RoomBooking 
          WHERE FK_BookingID IN 
            (SELECT FK_BookingID 
            FROM RoomBooking 
            WHERE FK_BookingID NOT IN 
             (SELECT BookingID 
              FROM Booking 
              WHERE CheckInDate <= '2017-10-04' 
              AND CheckOutDate > '2017-10-02') 
             ) 
            ) 
          ) 
         AND FK_BookingID NOT IN 
          (SELECT FK_BookingID 
          FROM RoomBooking 
          WHERE FK_BookingID NOT IN 
            (SELECT BookingID 
            FROM Booking 
            WHERE CheckInDate <= '2017-10-04' 
             AND CheckOutDate > '2017-10-02') 
            ) 
          ); 
+2

用你正在使用的數據庫標記你的問題。 –

+0

請格式化查詢以簡化閱讀。無需滾動時可讀性更高。 –

回答

3

我希望查詢是這樣的:

select r.* 
from room r 
where not exists (select 1 
        from roombooking rb join 
         booking b 
         on b.bookingid = r.bookingid 
        where r.roomid = rb.roomid and 
         '2017-10-02' < b.CheckOutDate and 
         '2017-10-04' >= b.CheckInDate 
       ); 

這是假定房間可供檢查在有人檢查了一天。

我不明白你爲什麼在fk_前加上一些列。外鍵關係應該明顯來自具有相同名稱的鍵(以及被明確聲明)。許多數據庫支持ANSI標準USING子句,並且具有不同的密鑰名稱會阻止您使用它。

+0

很快回答非常感謝!我對SQL很陌生,所以我不知道USING子句。謝謝你告訴我這個! – mike