¿Cómo devolver la imagen con la puntuación más alta para un producto determinado?

I have two tables, products and product_images. I have a third table 'product_categorys' too but I'm not sure how relevant this is for the question).

In the product Images table I have a column named score as an int as well as a product_id column. I would like to select a row or rows from the product table and have the highest scoring image return also. So far I have this:

SELECT `products`.*, `product_categorys`.`categoryName`, `product_categorys`.`categoryDescription`, `product_images`.`thumbName`
FROM (`products`)
INNER JOIN `product_categorys` ON `products`.`categoryID` = `product_categorys`.`pid`
left JOIN `product_images` ON `products`.`pid` = `product_images`.`productID`
WHERE `products`.`vendorID` =  '14'
AND `products`.`deleted` =  0
GROUP BY `products`.`pid`
ORDER BY `title` asc

Which returns a product image but not the highest scoring one, I'm not sure how to go about modifying this query (This has been generated by codeigniter) to give me what I need.

What needs to be changed/added to allow the query to return the highest scoring image please ?

preguntado el 08 de noviembre de 11 a las 11:11

1 Respuestas

I don't know it it works, but give it a try:

SELECT p.*, 
       pc.categoryName, pc.categoryDescription, 
       pim.thumbName, pim.score
FROM products p INNER JOIN product_categorys pc 
    ON p.categoryID = pc.pid
LEFT JOIN product_images pim 
    ON p.pid = pim.productID
WHERE p.vendorID =  '14'
  AND p.deleted =  0
  AND (pim.score = 
      (SELECT MAX(score) FROM product_images pim2 
       WHERE p.pid = pim2.productID)
   OR pim.score IS NULL)
GROUP BY p.pid

respondido 08 nov., 11:16

Thanks Marco, that's giving this error: Unknown column 'pim.id' in 'where clause'. - stack asker

thanks, this works but only shows product rows that have at least one corresponding row in the images table. - stack asker

Marco, you've got it bang on there, thank you very much for helping, much appreciated. - stack asker

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.