我試圖拉出最後10行的平均評級高於4的列表。現在這是通過從第一個表中選擇,然後檢查平均值,如果其上面4然後它被添加到一個變量,如果沒有,它什麼都不做。這是一個可怕的方法來做到這一點,特別是如果有超過1000行。MySQL選擇最後10行使用WHERE AVG()
這裏有兩個查詢:
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
謝謝,我用這個更快的變化(見上)0.2s對60.9s – spyke01 2012-04-26 23:05:21