MySQL LEFT JOIN不会返回所有结果

时间:2011-06-22 13:46:19

标签: mysql join

我有一个查询,请加入一些表格以获取产品列表,包括价格,图片,国家等。

“product_images”表可以包含零个或多个图像,但只应返回默认图像。我的问题是,无论如何,即使该特定产品的“product_images”表中没有图像,查询也应返回产品的结果。

第一个查询示例将为每个产品返回一行,但只返回一个随机图像:

SELECT `cp`.`category_id`, `p`.`id`, `p`.`master`, `p`.`status`, `p`.`sortorder`, `p`.`sku`, `p`.`stock`, `pd`.`name`, `pd`.`short_description`, `pd`.`description`, `pd`.`slug`, `pi`.`image`, `pi`.`path`
FROM `categories_products` AS `cp`
JOIN `products` AS `p` ON (`cp`.`product_id` = `p`.`id`)
JOIN `product_descriptions` AS `pd`
ON (`pd`.`product_id` = `p`.`id`)
LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id`)
WHERE `cp`.`category_id` = 34
AND `pd`.`locale_id` = 1
AND `p`.`master` = '0'
AND `p`.`status` = '1'
AND `p`.`accessible` = '1'
AND `pd`.`status` = '1'
GROUP BY `p`.`id`
ORDER BY `p`.`sortorder`

以下查询将返回默认图像。但是,如果“product_images”中没有图像,则不会检索该产品的行。唯一的区别在于此部分:“AND pipreset = 1”

SELECT `cp`.`category_id`, `p`.`id`, `p`.`master`, `p`.`status`, `p`.`sortorder`, `p`.`sku`, `p`.`stock`, `pd`.`name`, `pd`.`short_description`, `pd`.`description`, `pd`.`slug`, `pi`.`image`, `pi`.`path`
FROM `categories_products` AS `cp`
JOIN `products` AS `p` ON (`cp`.`product_id` = `p`.`id`)
JOIN `product_descriptions` AS `pd`
ON (`pd`.`product_id` = `p`.`id`)
LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id`)
WHERE `cp`.`category_id` = 34
AND `pi`.`preset` = 1
AND `pd`.`locale_id` = 1
AND `p`.`master` = '0'
AND `p`.`status` = '1'
AND `p`.`accessible` = '1'
AND `pd`.`status` = '1'
GROUP BY `p`.`id`
ORDER BY `p`.`sortorder`

2 个答案:

答案 0 :(得分:4)

 `pi`.`preset` = 1
WHERE中的

会破坏您的目标(您的LEFT JOIN的行为类似于INNER)。将其移至ON

LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id` AND `pi`.`preset` = 1)

答案 1 :(得分:2)

您可能更喜欢使用子查询:

LEFT JOIN (SELECT * FROM product_images WHERE preset = 1) AS pi ON ...

否则,WHERE子句将应用于整个查询,如果没有图像,WHERE pi.preset=1会将搜索集减少为零行。