Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count returning wrong value in a joined mysql query

I can not get the proper count of reviews that go with a product (the last var of the query). It is returning numbers that are way out of the park. Unless there are no reviews, then it properly echo's a 0.

$queryProduct = $mysqli->prepare("
    SELECT p.product_id, p.product_name, p.product_pic, AVG(r.review_stars), MIN(c.price_price), p.product_url, v.vendor_name, p.product_clicks, SUM(c.price_clicks), COUNT(c.price_price), c.price_affiliate, COUNT(r.review_id)
    FROM products as p 
    LEFT OUTER JOIN reviews as r ON p.product_id = r.review_product
    LEFT OUTER JOIN prices as c ON c.price_product = p.product_id
    LEFT OUTER JOIN vendors as v ON c.price_vendor = v.vendor_id
    GROUP BY p.product_id
    ORDER BY p.product_clicks DESC
    LIMIT 21");
$queryProduct->execute();
$queryProduct->bind_result($product_id, $product_name, $product_pic, $review_stars, $price_price, $product_url, $vendor_name, $product_clicks, $price_clicks, $num_vendors, $price_affiliate, $num_reviews);
while($queryProduct->fetch()) {
    echo $num_reviews;
}
$queryProduct->close();
like image 841
Katp00ps Avatar asked Apr 25 '26 12:04

Katp00ps


1 Answers

My wild guess is that you need COUNT(DISTINCT r.review_id).

To debug into this query, you'd start with checking a single product_id with bad value, and remove all the aggregates to check where the problem is. For example, I'd start from running

SELECT p.product_id, p.product_name, p.product_pic, r.review_stars, c.price_price, p.product_url, v.vendor_name, p.product_clicks, c.price_clicks, c.price_price, c.price_affiliate, r.review_id
FROM products as p 
LEFT OUTER JOIN reviews as r ON p.product_id = r.review_product
LEFT OUTER JOIN prices as c ON c.price_product = p.product_id
LEFT OUTER JOIN vendors as v ON c.price_vendor = v.vendor_id
WHERE p.product_id = 12345 -- choose a bad id in your output 
ORDER BY p.product_clicks DESC
like image 106
Xiangpeng Zhao Avatar answered Apr 27 '26 23:04

Xiangpeng Zhao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!