2

Here is my MySQL database:

enter image description here

And my query to get all subcategories:

SELECT `a`.`id`, `a`.`name`, `a`.`url_segment`, `a`.`categories_id`, `b`.`image` AS supplements_image
FROM (`subcategories` AS a)
LEFT JOIN `supplements` AS b ON `b`.`subcategories_id` = `a`.`id`
LEFT JOIN `reviews` AS c ON `c`.`supplements_id` = `b`.`id`
GROUP BY `a`.`id`
ORDER BY `a`.`categories_id` ASC, COUNT(c.id) DESC, `b`.`image` ASC

The problem is with the subcategory image, that should be the image of a random product inside that subcategory, but I'm always getting the image of the first product. Any idea how I can do this?

1 Answer 1

4
SELECT `a`.`id`, `a`.`name`, `a`.`url_segment`, `a`.`categories_id`, 
        (SELECT `image` 
         FROM `supplements` 
         WHERE `subcategories_id` = `a`.`id` 
         ORDER BY RAND() LIMIT 1
        ) AS supplements_image
FROM (`subcategories` AS a)
LEFT JOIN `reviews` AS c ON `c`.`supplements_id` = `a`.`id`
GROUP BY `a`.`id`
ORDER BY `a`.`categories_id` ASC, COUNT(c.id) DESC

Edited unspecified alias b and now works great: See fiddle!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.