1

我正在尝试提取平均评分高于 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
4

2 回答 2

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是您的朋友。

于 2012-04-26T20:50:57.263 回答
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
于 2012-04-26T20:49:07.273 回答