我正在尝试按以下方式运行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
,所以我没有结果。
该如何解决?
答案 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子句中-在加入之前将对其进行检查/应用。