MySQL联接行存在,但与Where语句不匹配

MySQL联接行存在,但与Where语句不匹配,mysql,Mysql,下面是两个表和一个select语句,我正试图使其发挥作用,但我遇到了一个问题。有人能帮我检查一下吗。(详情如下) 表`公司地点` id | company_id | location | deleted 1 | 1 | Las Vegas | 0 id | location_id | image | deleted 1 | 1 | company-name.las-vegas.15315

下面是两个表和一个select语句,我正试图使其发挥作用,但我遇到了一个问题。有人能帮我检查一下吗。(详情如下)

表`公司地点`

id | company_id | location  | deleted
1  | 1          | Las Vegas | 0
id | location_id | image                                 | deleted
1  | 1           | company-name.las-vegas.1531516751.jpg | 1
2  | 1           | company-name.las-vegas.1531516752.jpg | 1
3  | 1           | company-name.las-vegas.1531516753.jpg | 1
表格“位置图像”

id | company_id | location  | deleted
1  | 1          | Las Vegas | 0
id | location_id | image                                 | deleted
1  | 1           | company-name.las-vegas.1531516751.jpg | 1
2  | 1           | company-name.las-vegas.1531516752.jpg | 1
3  | 1           | company-name.las-vegas.1531516753.jpg | 1
选择语句:

SELECT `cl`.*, ifnull(li.image, "") AS image 
FROM `company_locations` `cl` 
LEFT JOIN `location_images` `li` 
    ON `li`.`location_id` = `cl`.`id` 
WHERE (`li`.`deleted` =0 OR `li`.`id` IS NULL) 
    AND `cl`.`deleted` =0 
ORDER BY `rating` DESC
如果
location\u images
表中没有公司位置的记录,它会完美地返回,但是因为有记录,它们与我没有得到结果的位置不匹配

编辑:

预期产出

cl.id | cl.company_id | cl.location  | image | cl.deleted
1     | 1             | Las Vegas    | NULL  | 0

您的
WHERE
语句正在使用

 `li.deleted =0`
但是,您的
位置\u图像中的所有记录都设置为
1
。那么不归还任何东西是正常的。请更新
位置图像中的记录并设置

deleted=0
以便查询按预期运行。

多亏了Raymond Nijland的建议,我才能够解决这个问题

SELECT `cl`.*, ifnull(li.image, "") AS image 
FROM `company_locations` `cl` 
LEFT JOIN (SELECT id, location_id, image FROM location_images WHERE deleted = 0) `li`
    ON (`li`.`location_id` = `cl`.`id` OR `li`.`id` IS NULL) 
WHERE `cl`.`deleted` =0 
ORDER BY `rating` DESC

我真的应该猜到这就是解决方案,但我忘了我可以在上的联接中添加一个

您需要将WHERE条件移动到左侧联接中的上。。或者左连接将被MySQL优化器重写为内部连接。我被这个问题弄糊涂了。如果你的where没有返回你想要的结果,那么为什么它是你的where?你能给出一些预期的结果吗?你能添加例外输出吗?我在帖子中添加了预期的输出。我还将研究Raymond的建议,即从连接中的SELECT中提取图像。