MySQL how to do COUNT(*) on a query with joins?
Does anyone know how can I perform COUNT(*) on a query like this?
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 开发者_Python百科=1
ORDER BY reviews.review_date DESC
Thanks!
Try this:
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
Left Join's are not needed, same as order, and you don't have to count all fields, one will be enough
SELECT COUNT(review_id) FROM reviews WHERE approved =1
EDIT:
if you want to count reviews for products than you should make something like this:
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
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
精彩评论