4

是否有可能做这样的事情:

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 条件

4

4 回答 4

7

这可以通过 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

注意:添加了 where to putORDER BY语句

查询优化器也不应该多次计算平均值,所以这里不应该担心。

正如@jagra's answer中提到的,您应该能够使用AVG()而不是SUM() / COUNT()

于 2013-03-26T17:46:59.200 回答
2

您可以使用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 vt.review_id = e.review_id 
GROUP BY `vt`.`review_id` 
HAVING rating >= 0;

由于您的问题被标记为 MySQL,因此该解决方案应该可以工作,如文档所示:

...在标准 SQL 中,包含 GROUP BY 子句的查询不能引用 HAVING 子句中未在 GROUP BY 子句中命名的非聚合列。MySQL 扩展允许引用此类列以简化计算。...

此扩展在官方 MySQL 编译中默认启用。

参考:http ://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html (页面上第一次出现的单词HAVING

于 2013-03-26T17:49:04.020 回答
1

通过聚合函数过滤时需要使用 HAVING 子句:

SELECT 
  # `e`.*, => is this needed
  `rt`.`review_id`, 
  (SUM(vt.percent) / COUNT(vt.percent)) AS rating 
  AVG(vt.percent) AS rating1 # same as above 
FROM `catalog_product_entity` AS `e` 
INNER JOIN `rating_option_vote` AS `vt`
  ON vt.review_id = e.review_id 
GROUP BY `vt`.`review_id`
HAVING AVG(vt.percent) > 0

另外两个注意事项:

1) SUM(x)/COUNT(x) <=> AVG(x)

2)您将 e.* 包括在 select 中,但不在 group by 中。MySql 允许您这样做,但其他数据库不会。

于 2013-03-26T18:05:19.690 回答
0

用于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 vt.review_id = e.review_id 
WHERE ( rating >= '0') 
GROUP BY `vt`.`review_id'
HAVING (SUM(vt.percent) / COUNT(vt.percent)) > 0
于 2013-03-26T17:49:43.333 回答