是否可以做这样的事情:
SELECT `e`.*, `rt`.`review_id`, (SUM(vt.percent) / COUNT(vt.percent)) AS rating FROM `catalog_product_entity` AS `e` INNER JOIN `rating_option_vote` AS `vt` ON vt.review_id = e.review_id WHERE (rating >= '0') GROUP BY `vt`.`review_id`
我尤其要在除法结果值上放置一个where条件
这可以通过HAVING子句完成:
SELECT e.*, rt.review_id, (SUM(vt.percent) / COUNT(vt.percent)) AS rating FROM catalog_product_entity AS e INNER JOIN rating_option_vote AS vt ON e.review_id = vt.review_id GROUP BY vt.review_id HAVING (SUM(vt.percent) / COUNT(vt.percent)) >= 0 ORDER BY (SUM(vt.percent) / COUNT(vt.percent)) ASC
注意:添加了放置ORDER BY语句的位置
ORDER BY
查询优化器也不应该多次计算平均值,因此在这里不必担心。
正如@jagra的答案中提到的那样,您应该可以使用AVG()而不是SUM() / COUNT()
AVG()
SUM() / COUNT()