2012-02-23 48 views
1

我有一些收集產品信息的sql。它還從連接的表中檢索圖像。有時產品會有多個圖像(有時不會),這會導致結果中出現重複。如何更改此查詢以僅從連接的圖像表中返回單個圖像(或無圖像) - image_d,image_p,image_t?如何僅從多個已連接的表中返回單個圖像行?

SELECT 
    products_categories.categoryid, 
    products.productid, 
    products.product, 
    products.descr, 
    products.rating, 
    products.title_tag, 
    images_d.image_path AS imaged, 
    images_p.image_path AS imagep, 
    images_t.image_path AS imaget, 
    clean_urls.clean_url 
FROM products_categories 
INNER JOIN products ON products_categories.productid = products.productid 
LEFT JOIN images_d ON products.productid = images_d.id 
LEFT JOIN images_p ON products.productid = images_p.id 
LEFT JOIN images_t ON products.productid = images_t.id 
LEFT JOIN clean_urls ON products.productid = clean_urls.resource_id 
WHERE products_categories.categoryid = 265 
AND products_categories.main = 'Y' 
AND products.forsale = 'Y' 
ORDER BY productid 

謝謝。

回答

1

我假設給定的image_x表中有多個圖像。您可以使用group_concat()多個值硬塞到一個CSV列:

SELECT 
    products_categories.categoryid, 
    products.productid, 
    products.product, 
    products.descr, 
    products.rating, 
    products.title_tag, 
    group_concat(images_d.image_path) AS imaged, 
    group_concat(images_p.image_path) AS imagep, 
    group_concat(images_t.image_path) AS imaget, 
    clean_urls.clean_url 
FROM products_categories 
INNER JOIN products ON products_categories.productid = products.productid 
LEFT JOIN images_d ON products.productid = images_d.id 
LEFT JOIN images_p ON products.productid = images_p.id 
LEFT JOIN images_t ON products.productid = images_t.id 
LEFT JOIN clean_urls ON products.productid = clean_urls.resource_id 
WHERE products_categories.categoryid = 265 
AND products_categories.main = 'Y' 
AND products.forsale = 'Y' 
GROUP BY 1,2,3,4,5,6,10 
ORDER BY productid 
+0

似乎並沒有得以順利,我還是得到重複的productid的返回。 – 2012-02-23 05:10:26

+0

@stackasker:難道是因爲重複產品屬於多個類別? – 2012-02-23 07:40:05

+0

@AndriyM:不,那不是。當我將提議的查詢更改爲2組時,它似乎會返回正確的結果。更多的睡眠,更多的測試。 – 2012-02-23 10:00:56

相關問題