这是对我之前问题的延伸,恰好是因为该项目在另一个表格中......
我有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'
我想我必须首先找到所有常规产品的总和,然后找到包装中的所有商品并计算运费并将它们加在一起。我对此有点新鲜。非常感谢帮助。
答案 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'
问题中的SQL中还有其他错误:
d
分配给packageitems
时,您无法在packageitems.PackageCode
子句中使用ON
,它必须是d.PackageCode
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'