MySQL如何对带有连接的查询执行COUNT(*)?

时间:2011-06-08 12:53:44

标签: mysql join count

有谁知道如何对这样的查询执行COUNT(*)?

SELECT reviews.review_id, reviews.reviewers_rating, reviews.reviewers_name, reviews.review_date, reviews.pros, reviews.cons, products.product_name, products.slug, products.community_rating, products.number_of_votes, products.users_rating, products.thumb_link, categories.category_name_single
FROM reviews
LEFT JOIN products ON reviews.product_id = products.product_id
LEFT JOIN categories ON products.category = categories.category_id
WHERE reviews.approved =1
ORDER BY reviews.review_date DESC

谢谢!

3 个答案:

答案 0 :(得分:1)

不需要左连接,与订单相同,并且您不必计算所有字段,一个就够了

SELECT COUNT(review_id) FROM reviews WHERE approved =1

编辑:
如果你想计算产品的评论而不是你应该做这样的事情:

SELECT products.*, count(r.review_id) AS reviews_count FROM products AS p
LEFT JOIN reviews AS r ON p.product_id = r.product_id AND r.approved=1
GROUP BY products.product_id

答案 1 :(得分:1)

试试这个:

SELECT Count(reviews.review_id), reviews.review_id, reviews.reviewers_rating, reviews.reviewers_name,  reviews.review_date, reviews.pros, reviews.cons, products.product_name, products.slug, products.community_rating, products.number_of_votes, products.users_rating, products.thumb_link, categories.category_name_single
FROM reviews
LEFT JOIN products ON reviews.product_id = products.product_id
LEFT JOIN categories ON products.category = categories.category_id
WHERE reviews.approved =1
Group By reviews.review_id
ORDER BY reviews.review_date DESC

答案 2 :(得分:0)

SELECT COUNT(*) FROM reviews
LEFT JOIN products ON reviews.product_id = products.product_id
LEFT JOIN categories ON products.category = categories.category_id
WHERE reviews.approved = 1 AND ...
ORDER BY reviews.review_date DESC