我有两张桌子,产品和product_images。我有第三张桌子&product; categorys'我也不确定这个问题的相关性如何)。
在产品Images表中,我有一个名为score的列作为int以及product_id列。我想从产品表中选择一行或多行,并获得最高得分图像。到目前为止,我有这个:
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
返回产品图片但不是最高得分的图片,我不知道如何修改此查询(这是由codeigniter生成的),以便为我提供所需内容。
需要更改/添加哪些内容才能让查询返回得分最高的图片?
答案 0 :(得分:2)
我不知道它有效,但试一试:
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