【问题标题】:SUM() not working correctly when left joining Many to Many table离开加入多对多表时,SUM() 无法正常工作
【发布时间】:2016-04-05 11:00:13
【问题描述】:

注意:我看到了类似的 SQL 问题,但没有关于如何解决这个问题的特定于 MySQL 的问题。

我有以下查询,它根据销售表中的销售日期按天计算产品价值,可以根据类别过滤产品,这就是我需要左连接的原因,类别也需要与其余信息一起显示。由于项目要求,我无法在此 MySQL 查询之外进行任何处理。

select `sales`.`sell_date` as `date`, SUM(product_value.value) as value from 
   `sales` left join `products` on `sales`.`product_id` = `products`.`id` left join
   `product_value` on `product_value`.`product_id` = `products`.`id` and 
   `sales`.`sell_date` BETWEEN product_value.date_from AND 
   IFNULL(product_value.date_to, '2999-01-01') 
   left join `product_product_category` on `product_product_category`.`product_id` 
   = `products`.`id` left join `product_categories` on 
   `product_product_category`.`product_category_id` = `product_categories`.`id` 
   left join `users` on `sales`.`seller_id` = `users`.`id` 
   where `sales`.`sell_date` between "2016-02-01" and "2016-02-29" and `product_value`.`deleted_at` is null 
   and `products`.`id` in ("178") and `sales`.`deleted_at` is null group by 
  `sales`.`sell_date` order by `sales`.`sell_date` asc

当一个产品有两个或三个类别时,上面的查询将得到一个加倍或三倍的总和。类别可以是颜色、大小等。

当我从查询中删除以下内容时,总和工作正常,这让我相信这里的多对多关系导致了问题。

left join `product_product_category` on `product_product_category`.`product_id` =
 `products`.`id` left join `product_categories` on
 `product_product_category`.`product_category_id` = `product_categories`.`id`

如何防止这个左连接导致我的 SUM() 给我错误的总值?

对 product_value.value 使用 Distinct 将不起作用,因为许多产品的产品值可能相同。

我的桌子

销售额

ID | sell_date  | product_id
----------------------------
2  | 2016-02-15 | 178

产品价值

ID | value | date_from  | date_to    | product_id
-------------------------------------------------
1  | 500   | 2016-01-01 | NULL       | 178
2  | 500   | 2015-01-01 | 2015-12-01 | 392

产品

ID | name
----------
178  | ProductName

product_product_category

product_id | product_category_id
--------------------------------
178        | 1
178        | 2

产品类别

ID | name
---------
1  | Red
2  | Large

所以为了清楚起见,如果我在这些表上运行上述查询,我​​会得到 value = 1000,但 value 应该是 500。如何确保 SUM() 在加入多对多时显示正确的值关系?

【问题讨论】:

    标签: mysql join many-to-many


    【解决方案1】:

    您可以删除left join 并在where 中添加过滤器作为子查询

    ...
    where
    ...
    and exists (
        select 1
        from `product_product_category`
            inner join `product_categories` on `product_product_category`.`product_category_id` = `product_categories`.`id` 
        where `product_product_category`.`product_id` = `products`.`id`
            and ....
            and ....
    )
    ...
    

    【讨论】:

      猜你喜欢
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 2013-03-27
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多