Two left joins gives me untrue data(double data?) with MySQL

后端 未结 3 1353
梦谈多话
梦谈多话 2021-01-26 06:56

This is my query:

SELECT `products`.*, SUM(orders.total_count) AS revenue,
    SUM(orders.quantity) AS qty, ROUND(AVG(product_reviews.stars)) as avg_stars 
FROM          


        
3条回答
  •  一个人的身影
    2021-01-26 07:36

    The problem is that the product_reviews and orders table can have more that one row per product id. One way you can fix this is to use a subquery:

    SELECT `products`.*, 
      o.revenue,
      o.qty, 
      ROUND(avg_stars) as avg_stars 
    FROM `products` 
    LEFT JOIN
    (
      select `product_id`, 
        sum(total_count) revenue,
        sum(quantity) qty
      from `orders`
      where `status` in ('delivered', 'new')
      group by `product_id`
    ) o
      ON `products`.`id` = o.`product_id`
    LEFT JOIN
    (
      select product_id, avg(stars) avg_stars
      from product_reviews
      group by product_id
    ) pr
        ON (products.id = pr.product_id)
    ORDER BY products.ID DESC
    LIMIT 10
    OFFSET 0
    

提交回复
热议问题