MySQL使用WHERE AVG选择最近10行()

时间:2012-04-26 20:45:35

标签: mysql group-by average

我正在尝试提取平均评分高于4的最后10行的列表。现在通过从第一个表中选择然后检查平均值是否超过4来完成,然后将其添加到变量中,如果不是它什么都不做。这是一种可怕的方法,特别是如果有超过1000行。

以下是两个查询:

SELECT * FROM `CLMS_reviews` WHERE id = 465 ORDER BY date DESC

SELECT 
rc.name, rr.rating
FROM `CLMS_reviews_ratings` rr  
LEFT JOIN `CLMS_reviews_categories` rc ON rc.cat_id = rr.cat_id  AND rc.website_id = 465
WHERE rr.review_id = " . $row['id'] . "
GROUP BY rc.name

如何将其合并为一个查询?我试过这个,但无效使用GROUP BY:

SELECT 
rr.review_id
FROM `CLMS_reviews` r
LEFT JOIN `CLMS_reviews_ratings` rr ON rr.review_id = r.id
WHERE r.website_id = 465 AND AVG(rr.rating) > 4
GROUP BY rr.review_id LIMIT 10

解决方案从下面:

SELECT review_id FROM `CLMS_reviews_ratings`
WHERE review_id IN ((SELECT id FROM `CLMS_reviews` WHERE website_id = 465))
GROUP BY review_id
HAVING avg(rating) > 4
LIMIT 10

2 个答案:

答案 0 :(得分:2)

无法测试,但也许会这样做:

SELECT rr.review_id
  FROM `CLMS_reviews` r
  LEFT JOIN `CLMS_reviews_ratings` rr ON rr.review_id = r.id
 WHERE r.website_id = 465
 GROUP BY rr.review_id
HAVING avg(rr.rating) > 4
 LIMIT 10;

如果您需要过滤汇总功能,HAVING就是您的自由。

答案 1 :(得分:1)

我认为您需要使用HAVING语法。像这样:

SELECT 
rr.review_id
FROM `CLMS_reviews` r
LEFT JOIN `CLMS_reviews_ratings` rr ON rr.review_id = r.id
WHERE r.website_id = 465
GROUP BY rr.review_id 
HAVING AVG(rr.rating) > 4
LIMIT 10