MySQL Join Query从来自多个表的产品中获取购物车表中的项目总和

时间:2016-03-03 20:19:21

标签: mysql

这是对我之前问题的延伸,恰好是因为该项目在另一个表格中......

我有4张桌子:

+------------+----------+------------+---------+
| customerid | itemcode | cartactive |  type   |
+------------+----------+------------+---------+
|       9916 | X        | Yes        | Package |
|       9916 | Y        | Yes        | Product |
+------------+----------+------------+---------+

产品

+-------------+------------+
| ProductCode | shipWeight |
+-------------+------------+
| Y           |          1 |
| ITEM1       |          1 |
| ITEM2       |          2 |
| ITEM3       |          1 |
+-------------+------------+

+-------------+
| PackageCode |
+-------------+
| X           |
+-------------+

PackageItems

+-------------+-------------+
| PackageCode | ProductCode |
+-------------+-------------+
| X           | ITEM1       |
| X           | ITEM2       |
| X           | ITEM3       |
+-------------+-------------+

所以基本上但不容易我试图获得我们在这里看到的购物车中所有商品的总和应为5。

以下是我写的返回不唯一表/别名的查询:'产品'

Select 
SUM(products.shipWeight) as totalweight 
FROM 
cart 
Left JOIN products  ON products.ProductCode = cart.itemCode
LEFT JOIN packageitems d on cart.itemCode = packageitems.PackageCode
LEFT JOIN products on d.ItemCode = products.ProductCode
 WHERE 
cart.customerId= '9916' AND 
cart.cartActive = 'Yes'

我想我必须首先找到所有常规产品的总和,然后找到包装中的所有商品并计算运费并将它们加在一起。我对此有点新鲜。非常感谢帮助。

3 个答案:

答案 0 :(得分:2)

由于您已经两次加入products表,因此您需要使用别名来区分应使用哪个实例。

Select 
    SUM(p2.shipWeight) as totalweight 
FROM cart 
Left JOIN products AS p1 ON p1.ProductCode = cart.itemCode
LEFT JOIN packageitems d on cart.itemCode = d.PackageCode
LEFT JOIN products AS p2 on d.ProductCode = p2.ProductCode
WHERE 
    cart.customerId= '9916' AND 
    cart.cartActive = 'Yes'

DEMO

问题中的SQL中还有其他错误:

  1. 当您将别名d分配给packageitems时,您无法在packageitems.PackageCode子句中使用ON,它必须是d.PackageCode
  2. itemCode中没有packageitems,因此d.itemCode错误,应为d.ProductCode

答案 1 :(得分:0)

只需使用OR

加入

<强> SQL Fiddle Demo

我没有包含SUM,因此您可以看到结果。

SELECT c.`itemcode`, pi.`ProductCode`, p.`ProductCode`, p.`shipWeight`
FROM cart c
LEFT JOIN PackageItems pi
       ON c.`itemcode` = pi.`PackageCode`
LEFT JOIN products p
       ON p.`ProductCode` = c.`itemcode`
       OR p.`ProductCode` = pi.ProductCode 
WHERE c.`customerid`= '9916' AND 
c.`cartactive` = 'Yes'

答案 2 :(得分:0)

重命名表并在条件的连接中使用别名。

Select SUM(prod2.shipWeight) as totalweight
FROM 
cart
Left JOIN products prod1  ON prod1.ProductCode = cart.itemCode
LEFT JOIN packageitems d on cart.itemCode = d.PackageCode
LEFT JOIN products prod2 on d.ItemCode = prod2.ProductCode
WHERE 
cart.customerId= '9916' AND 
cart.cartActive = 'Yes'