MySQL Join将结果倍增

时间:2014-09-30 16:52:05

标签: mysql sql join

我遇到了将两张桌子连在一起的问题,它不断增加我的价值“qtyFulfillable”。

1,当我运行此查询时,我得到了正确的结果: sumQF = 85

 SELECT fbai.id, 
        fbai.sku,
        CASE WHEN SUM(fbai.qtyFulfillable) > 0 THEN SUM(fbai.qtyFulfillable) ELSE 0 END AS sumQF
 FROM FBAInventory fbai
 WHERE fbai.fbaInventoryReport_id = 62010
 AND     fbai.sku = 'ELO-250030'
 GROUP BY fbai.id
 ORDER BY sumQF DESC

但是当我开始添加联接时,我现在得到: sumQF = 14110

 SELECT fbai.id, 
        fbai.sku,
        CASE WHEN SUM(fbai.qtyFulfillable) > 0 THEN SUM(fbai.qtyFulfillable) ELSE 0 END AS sumQF, 
        CASE WHEN   SUM(fbas.quantityShipped) > 0 THEN SUM(fbas.quantityShipped) ELSE 0 END as sumQS
 FROM FBAInventory fbai
 LEFT JOIN  FBAShipment fbas
 ON fbai.sku = fbas.sku
 WHERE fbai.fbaInventoryReport_id = 62010
 AND     fbai.sku = 'ELO-250030'
 GROUP BY fbai.id
 ORDER BY sumQF DESC

由于某种原因,sql获取“fbas”表(连接表)中的总行数,166行,并乘以 85 x 166 = 14110

我需要做什么才能加入此表,但不要将我的结果乘以连接表中的总行数。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在单独的查询中汇总第二个数量,并JOIN将其汇总。我还想使用GREATEST而不是CASE语句。

    SELECT fbai.id,
           fbai.sku,
           GREATEST(SUM(fbai.qtyFulfillable),0) sumQF,
           COALESCE(fbas_sum.value,0) sumQS /* COALESCE in case no rows */
      FROM FBAInventory fbai
 LEFT JOIN (
        SELECT sku,
               GREATEST(SUM(quantityShipped),0) value
          FROM FBAShipment
      GROUP BY sku
           ) fbas_sum
        ON fbas_sum.sku=fbai.sku
     WHERE fbai.fbaInventoryReport_id=62010
       AND fbai.sku='ELO-250030'
  GROUP BY id, sku, sumQS /* Added other non-aggregates for sanity */
  ORDER BY sumQF DESC

您确定要对id进行分组吗?我认为id是表的主键,所以应该只有一行要求和。