SQL:LEFT OUTER JOIN的帮助

时间:2009-06-24 19:02:56

标签: sql database database-design query-optimization

我的SQL似乎不是基于price限制结果。

在我之前的帖子SQL: Help me optimize my SQL中,有人表示我应该使用LEFT OUTER JOIN。

SELECT homes.home_id, 
    address, 
    city, 
    state, 
    zip, 
    price, 
    photo_id, 
    photo_url_dir
FROM homes
LEFT OUTER JOIN home_photos ON homes.home_id = home_photos.home_id
AND primary_photo_group_id = home_photo_group_id
AND home_photo_type_id =2
AND display_status = true
AND homes.price BETWEEN 500000 AND 1000000

然而,它仍然显示价格<1的房屋。 500000

我不明白。当我有一个WHERE条件来限制该字段时,为什么上面的SQL会显示价格低于500000的房屋。

感谢您的帮助。

我想做什么

我想基于X和Y之间的PRICE标准,或者SQFT&gt;来显示家庭和家庭没有home_photo Z.但是这些标准需要适用于那些有homes而没有home_photo

的家庭。

这是正确的吗?

SELECT homes.home_id, 
    address, 
    city, 
    state, 
    zip, 
    price, 
    photo_id, 
    photo_url_dir
FROM homes
LEFT OUTER JOIN home_photos ON homes.home_id = home_photos.home_id
    AND homes.primary_photo_group_id = home_photos.home_photo_group_id
    AND home_photos.home_photo_type_id =2
WHERE homes.display_status = true
AND homes.price BETWEEN 500000 AND 1000000

4 个答案:

答案 0 :(得分:19)

最后一行应该使用WHERE而不是

WHERE homes.price BETWEEN 500000 AND 1000000

最终结果是以下SQL:

SELECT 
    homes.home_id, 
    homes.address, 
    homes.city, 
    homes.state, 
    homes.zip, 
    homes.price, 
    home_photos.photo_id, 
    home_photos. photo_url_dir
FROM 
    homes
    LEFT OUTER JOIN home_photos ON 
        homes.home_id = home_photos.home_id
        AND homes.primary_photo_group_id = home_photos.home_photo_group_id
        AND home_photos.home_photo_type_id =2
WHERE
    homes.price BETWEEN 500000 AND 1000000
    AND homes.display_status = true

编辑

现在您的SQFT将在WHERE

之前
AND home_photos.home_photo_type_id =2 
AND SQFT <=2000 
WHERE homes.price BETWEEN 500000 AND 1000000

答案 1 :(得分:0)

在JOIN关键字之后使用连接条件,在WHERE子句之后使用所有其他过滤条件

答案 2 :(得分:0)

试试这个......

SELECT homes.home_id,     
address,     
city,     
state,     
zip,     
price,     
photo_id,     
photo_url_dir
FROM 
homes
LEFT OUTER JOIN 
home_photos ON homes.home_id = home_photos.home_id
AND 
primary_photo_group_id = home_photo_group_id
WHERE 
home_photo_type_id =2
AND 
display_status = true
AND 
homes.price BETWEEN 500000 AND 1000000

答案 3 :(得分:0)

您拥有join中的所有条件,您应该在where子句中使用其中一些来限制查询。类似的东西:

select
   homes.home_id, 
   address, 
   city, 
   state, 
   zip, 
   price, 
   photo_id, 
   photo_url_dir
from
   homes
left join
   home_photos on homes.home_id = home_photos.home_id
where
   primary_photo_group_id = home_photo_group_id and
   home_photo_type_id = 2 and
   display_status = true and
   homes.price BETWEEN 500000 AND 1000000

由于我不知道每个字段来自哪个表,我不知道上述内容是否有意义。在joinwhere之间划分条件。