如何仅从多个连接表返回单个图像行?

时间:2012-02-23 04:43:10

标签: mysql sql

我有一些收集产品信息的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 个答案:

答案 0 :(得分: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