[英]MySQL SELECT from 2 different Tables with WHERE clause on 2 Tables and 1 result NULL
I am trying to get the ordered qty in the cart_items
table and the shipped qty in the shipping_table
. 我试图让在有序数量 cart_items
表,并在出厂的数量 shipping_table
。 Problem is, some skus
haven't shipped yet and I can either A) only pull the items shipped or B) not have the correct total shipped qty. 问题是,有些skus
还没有发货,我可以A)仅拉出已发货的物品,或者B)没有正确的总发货数量。
SAMPLE DATA 样本数据
`shipping_table`
id | invoice | sku | qty | order_id
99 | 104 | 15628 | 1 | 9313
98 | 104 | 34929 | 2 | 9313
97 | 103 | 34929 | 1 | 9313
96 | 102 | 15628 | 87 | 9999
95 | 101 | 34929 | 32 | 9999
94 | 100 | 35870 | 6 | 9999
`cart_items`
id | cart_id | sku | qty
64903 | 4935153 | 15628 | 1
65108 | 4935153 | 34929 | 4
65109 | 4935153 | 35870 | 4
In this result we should see that sku 35870 hasn't shipped any items, 15628 has shipped, and sku 34929 only has shipped 3 items. 在此结果中,我们应该看到sku 35870没有发货,15628已经发货,而sku 34929只发货了3件。
EXPECTED RESULT 预期结果
sku | total_qty | total_shipped_qty
15628 | 1 | 1
34929 | 4 | 3
35870 | 4 | NULL
WRONG RESULT A 错误的结果A.
This one is close but since I am querying on an order_id
which is only in one table it doesn't pull the total_qty
for the sku 35870 because it is not in shipping_table
yet (it hasn't shipped at all). 这是接近的,但是由于我正在查询仅在一个表中的order_id
,因此它不会为sku 35870拉出total_qty
,因为它尚未在shipping_table
(它根本没有发货)。
SELECT
CT.sku,
MT.`qty` as total_qty,
SUM(CT.`qty`) as total_shipped_qty
FROM `shipping_table` CT
LEFT JOIN
`cart_items` MT ON MT.sku = CT.sku
WHERE MT.`cart_id` = '4935153' AND CT.`order_id` = '9313'
GROUP BY MT.sku
sku | total_qty | total_shipped_qty
15628 | 1 | 1
34929 | 4 | 3
WRONG RESULT B 错误结果B
Here is something close but it is the incorrect total_shipped_qty
values because it is looking at the Total in the whole shipping_table
. 这是关闭的东西,但它是不正确的total_shipped_qty
值,因为它正在查看整个shipping_table
中的Total。 This result looks like it sums up the WHOLE qtys for the shipping_table
. 这个结果看起来像它总结了整个qtys为shipping_table
。
SELECT
CT.sku,
MT.`qty` as total_qty,
SUM(CT.`qty`) as total_shipped_qty
FROM `shipping_table` CT
LEFT JOIN
`cart_items` MT ON MT.sku = CT.sku
WHERE MT.`cart_id` = '4935153'
GROUP BY MT.sku
sku | total_qty | total_shipped_qty
15628 | 1 | 88
34929 | 4 | 35
35870 | 4 | 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.