2011-06-22 121 views
1

我有一個連接的某些表,以獲得產品列表,包括價格,圖片等國家的MySQL LEFT 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」中沒有圖像,則不會檢索該產品的行。這裏唯一的不同是這部分 「以及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` 
+0

你使用'LEFT JOIN',那麼左表中的所有數據都將被檢索,而不是使用'RIGHT JOIN' – diEcho

回答

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) 
+0

啊,比我的子查詢解決方案更加出色! – mingos

2

您可能更願意使用子查詢:

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

否則,WHERE子句應用到整個查詢,如果沒有圖像,WHERE pi.preset=1會降低你的搜索設置爲零行。