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 LIMIT 10
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
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 ORDER BY title ASC LIMIT 10