我在SQL Server中建立了一個酒店預訂數據庫。表中的三個是如下:SQL太複雜的嵌套查詢 - 你能簡化一下嗎?
相關列的表中有:
Booking
:BookingID
(PK),CheckInDate
,CheckoutDate
RoomBooking
:RoomBookingID
(PK),FK_Booking_ID
(FK),FK_RoomID
(FK)Room
:RoomID
(PK)
現在我寫了一個SQL查詢(如下所示),試圖找出在某個日期(2017-10-02到2017-10-04)哪些房間是免費的。代碼解決了這個問題,但變得非常複雜。我知道如何通過在表RoomBooking
中使CheckInDate
和CheckOutDate
更容易地解決這個問題,但我希望此設置能夠正常工作。你有什麼想法如何簡化下面的代碼?
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')
)
);
用你正在使用的數據庫標記你的問題。 –
請格式化查詢以簡化閱讀。無需滾動時可讀性更高。 –