MySQL:使用带有WHERE子句的JOINS从一个表获取所有记录,从另一个表获取可用记录

时间:2020-10-09 05:41:54

标签: mysql sql left-join having-clause

我正在尝试按以下方式运行SQL查询

SELECT organization.idorganization,
organization.name,
organization.image_url,
organization.website,
organization.description,
organization.phone,
organization.email,
organization.spare_parts_items,
organization.specialty_vehicles,
organization.on_the_spot_service,
organization.home_visits,
organization.latitude,
organization.longitude,
organization.no_of_views,
 organization.is_disabled,
organization.date_created,
organization.last_update,
organization.address,
cover_photo.idcover_photo,
cover_photo.image_url,
cover_photo.thumbnail,
( 6371 * acos( cos( radians(7.294324) ) * cos( radians( organization.latitude ) ) * cos( radians( organization.longitude ) - radians(80.646185) ) 
+ sin( radians(7.294324) ) * sin( radians( organization.latitude ) ) ) ) AS distance 
FROM organization 
LEFT OUTER JOIN cover_photo ON cover_photo.idcover_photo = organization.idorganization
WHERE organization.idorganization_type =1 HAVING distance < 20 AND cover_photo.thumbnail=true

在这里,我期望从organization获取所有记录,无论是否有cover_photo。因此,我使用了LEFT OUTER JOIN。但是,如果它有cover_photo,它应该只得到thumbnail的那些。 cover_photo每个organization包含一张以上的照片。

运行代码时,我没有得到想要的东西。如果thumbnails表中没有cover_photo可用,则该特定organization将被完全忽略。目前,我没有任何组织的cover_photo,所以我没有结果。

该如何解决?

2 个答案:

答案 0 :(得分:2)

基本上,您需要将LEFT JOIN表上的条件从WHERE子句移到ON的{​​{1}}子句:否则,它成为强制性的,并过滤掉LEFT JOIN不匹配的行。

即,更改此内容:

LEFT JOIN

收件人:

LEFT OUTER JOIN cover_photo 
    ON  cover_photo.idcover_photo = organization.idorganization
WHERE organization.idorganization_type = 1 AND cover_photo.thumbnail = true
HAVING distance < 20

答案 1 :(得分:0)

AND cover_photo.thumbnail=true移至ON子句表达式:

... 
FROM organization  
LEFT OUTER JOIN cover_photo ON cover_photo.idcover_photo = organization.idorganization 
                           AND cover_photo.thumbnail=true 
WHERE organization.idorganization_type =1 
HAVING distance < 20 

LEFT JOIN中右表中的一列所产生的条件(除了直接或间接检查此列是否为NULL以及空安全比较之外)会弹出所有右表中没有匹配行的行。但是INNER和LEFT联接之间的区别是这些左无右行-即条件将LEFT JOIN转换为INNER JOIN。

因此,必须将此条件置于ON子句中-在加入之前将对其进行检查/应用。