2013-01-23 113 views
0

任何人都可以幫助我與我的SQL語句如下。我試圖做的是從1表中檢索行,他們不出現在另一個表的日期範圍內。此時下面的查詢返回輸入日期範圍之間的行。我如何修改它,以便表2中的日期範圍之間的行不會從表1返回?表1是家庭和表2是預訂Oracle SQL從一個表中選擇行不在另一個

SELECT homes.home_id, homes.title, homes.description, homes.living_room_count, homes.bedroom_count, homes.bathroom_count, homes.price, homes.sqft, 
listagg(features.feature_name, '\n') WITHIN GROUP(ORDER BY features.feature_name) features, home_type.type_name 
FROM homes 
INNER JOIN bookings ON bookings.home_id = homes.home_id 
INNER JOIN home_feature ON homes.home_id = home_feature.home_id 
INNER JOIN home_type ON home_type.type_code = homes.type_code 
INNER JOIN features ON home_feature.feature_id = features.feature_id 
WHERE bookings.booking_end < to_date('23-Jan-13') 
OR bookings.booking_start > to_date('22-Jan-13') 
GROUP BY homes.home_id, homes.title, homes.description, homes.living_room_count, homes.bedroom_count, homes.bathroom_count, homes.price, homes.sqft, home_type.type_name 

回答

3

您將要使用LEFT JOIN返回從homes沒有出現在bookings所有行。我也建議從WHERE條款移動bookings.date過濾到JOIN條件:

SELECT homes.home_id, 
    homes.title, 
    homes.description, 
    homes.living_room_count, 
    homes.bedroom_count, 
    homes.bathroom_count, 
    homes.price, homes.sqft, 
    listagg(features.feature_name, '\n') WITHIN GROUP(ORDER BY features.feature_name) features, 
    home_type.type_name 
FROM homes 
LEFT JOIN bookings 
    ON bookings.home_id = homes.home_id 
    AND (bookings.booking_end < to_date('23-Jan-13') 
    OR bookings.booking_start > to_date('22-Jan-13')) 
LEFT JOIN home_feature 
    ON homes.home_id = home_feature.home_id 
LEFT JOIN home_type 
    ON home_type.type_code = homes.type_code 
LEFT JOIN features 
    ON home_feature.feature_id = features.feature_id 
GROUP BY homes.home_id, homes.title, 
    homes.description, homes.living_room_count, 
    homes.bedroom_count, homes.bathroom_count, 
    homes.price, homes.sqft, home_type.type_name 

基於您的評論,你可以嘗試NOT EXISTS

SELECT homes.home_id, 
    homes.title, 
    homes.description, 
    homes.living_room_count, 
    homes.bedroom_count, 
    homes.bathroom_count, 
    homes.price, homes.sqft, 
    listagg(features.feature_name, '\n') WITHIN GROUP(ORDER BY features.feature_name) features, 
    home_type.type_name 
FROM homes 
INNER JOIN home_feature 
    ON homes.home_id = home_feature.home_id 
INNER JOIN home_type 
    ON home_type.type_code = homes.type_code 
INNER JOIN features 
    ON home_feature.feature_id = features.feature_id 
WHERE NOT EXISTS (SELECT home_id 
        FROM bookings b 
        WHERE b.home_id = homes.home_id 
        AND (b.booking_end < to_date('23-Jan-13') 
         OR b.booking_start > to_date('22-Jan-13')) 
GROUP BY homes.home_id, homes.title, 
    homes.description, homes.living_room_count, 
    homes.bedroom_count, homes.bathroom_count, 
    homes.price, homes.sqft, home_type.type_name 
+0

您好,感謝您的答覆。我試過了你的查詢,並且當它在日期範圍之間應該省略時,它將返回來自家庭表的所有行。 – user1851487

+0

@ user1851487糟糕,錯過了你的解釋。看我的編輯 – Taryn

相關問題