我有3个名为rsales
,rreturn
,productlist
的表格。表格rsales
和rreturn
包含total
列。我的目标是,我想要汇总来自total
表的rsales
和total
值的所有rreturn
值,并仅从productlist
表中选择特定值。
比方说,我从productlist
表中获得了这些数据:
id | pcode | pname | pdesc |
1 | 222 | 33uf | 10v |
来自rsales
表的数据:
id | total | pcode |
1 | 200 | 222 |
2 | 200 | 222 |
来自rreturn
表的数据:
id | total | pcode |
1 | 50 | 222 |
2 | 20 | 222 |
输出必须是这样的:
id | pcode | pname | pdesc | total
1 | 222 | 33uf | 10v | 470
我的问题是:我想对total
和rsales
表中的所有rreturn
值求和,并从productlist
中选择所有值。我在下面有以下代码,运行得很好。但它只能从rsales
表中总计总值,或者更确切地说,它只能从一个表中求和。
$result = mysql_query("SELECT
productlist.*,
SUM(rsales.total) as total,
SUM(rsales.vatable_sales) as vatable_sales,
SUM(rsales.vats) as vats,
SUM(rsales.discount) as discount
FROM productlist
LEFT JOIN rsales ON rsales.pcode = productlist.pcode
GROUP BY pcode
ORDER BY total ASC");
答案 0 :(得分:1)
你不清楚哪些不适合你。你得到的结果,但数字不是你所期望的?好吧,假设您有三个销售和两个退货,那么您通过加入所有表格获得六个记录。因此,您的销售额翻倍,回报增加三倍。
您可以为一个解决方案加入聚合:
$result = mysql_query("SELECT
productlist.*,
sumsales.sum_total + sumreturns.sum_total as total,
sumsales.sum_vatable_sales as vatable_sales,
sumsales.sum_vats as vats,
sumsales.sum_discount as discount
FROM productlist
LEFT JOIN
(
SELECT pcode, SUM(total) as sum_total, SUM(vatable_sales) as sum_vatable_sales, SUM(vats) as sum_vats, SUM(discount) as sum_discount
FROM rsales
GROUP BY pcode
) AS sumsales ON sumsales.pcode = productlist.pcode
LEFT JOIN
(
SELECT pcode, SUM(total) as sum_total
FROM rreturn
GROUP BY pcode
) AS sumreturns ON sumreturns.pcode = productlist.pcode
ORDER BY total ASC");