Oracle SQL从一个表中选择不在另一个表中的行

时间:2013-01-23 11:55:19

标签: sql oracle join oracle11g

任何人都可以帮我解决下面的sql语句。我想要做的是从1个表中检索行,它们不会出现在另一个表的日期范围内。此时的查询返回输入日期范围之间的行。我怎么能修改它,以便从表1返回不在表2中的日期范围之间的行?表1将是家庭,表2将是预订

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

1 个答案:

答案 0 :(得分:3)

您需要使用LEFT JOIN返回homes中未显示在bookings中的所有行。我还建议将bookings.date过滤器从WHERE子句移到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