2

这是我的 MySQL 数据库:

在此处输入图像描述

我的查询以获取所有子类别:

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

问题在于子类别图像,它应该是该子类别中随机产品的图像,但我总是得到第一个产品的图像。知道我该怎么做吗?

4

1 回答 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

编辑了未指定的别名b,现在效果很好:见小提琴!

于 2012-11-20T17:56:32.477 回答