Php 从两个不同的表中减去
我有3个表“productlist,sales,return”,比如我有3个sales和2个return,如下所示 这是productlist中的ff数据Php 从两个不同的表中减去,php,mysql,Php,Mysql,我有3个表“productlist,sales,return”,比如我有3个sales和2个return,如下所示 这是productlist中的ff数据 id | pcode | pname | pdesc | 1 | 222 | 33uf | 10v | 这是来自销售的ff数据 id | pcode | total | profit 1 | 222 | 200 | 10 2 | 222 | 100 | 10 3 | 222 | 200 |
id | pcode | pname | pdesc |
1 | 222 | 33uf | 10v |
这是来自销售的ff数据
id | pcode | total | profit
1 | 222 | 200 | 10
2 | 222 | 100 | 10
3 | 222 | 200 | 10
这是返回的ff数据
id | pcode | total | lose
3 | 222 | 200 | 10
4 | 222 | 100 | 10
我的问题是这个。我想从productlist中选择数据,对销售的“总计”和“利润”值求和,对退货的“总计”和“损失”值求和。然后减去我的两张表得到结果。预期的结果一定是这样的
id | pcode | pname | pdesc | total | profit |
1 | 222 | 33uf | 10v | 200 | 10 |
我有这个ff代码,但我不能从销售中减去“总计”,从退货中减去“总计”,从销售中减去“利润”,从退货中减去“损失”
$result = mysql_query("SELECT
productlist.*,
SUM(sales.total)-SUM(return.total) as total,
SUM(sales.profit)-SUM(return.lose) as profit
FROM productlist
LEFT JOIN sales ON sales.pcode = productlist.pcode AND return ON return.pcode = productlist.pcode
GROUP BY pcode
ORDER BY total ASC");
您似乎试图用
和连接两个表,这不太正确;)
试试这个:
...
LEFT JOIN `sales` USING (`pcode`)
LEFT JOIN `return` USING (`pcode`)
...
我不完全确定这是否有效,它可能会抱怨列'pcode'不明确
。如果发生这种情况,请尝试以下方法:
...
LEFT JOIN `sales` ON `sales`.`pcode` = `productlist`.`pcode`
LEFT JOIN `return` ON `return`.`pcode` = `productlist`.`pcode`
...
查询的结构不会返回正确的结果。无论您如何修改语法,对于给定的产品,您仍然会在销售和退货之间获得笛卡尔乘积
一种修复方法是在联接之前进行聚合:
SELECT pl.*,
(coalesce(s.total, 0) - coalesce(r.total, 0)) as total,
(coalesce(s.profit, 0) - coalesce(r.lose, 0)) as profit
FROM productlist pl left join
(select pcode, sum(total) as total, sum(profit) as profit
from sales
group by pcode
)
on s.pcode = pl.pcode left join
(select pcode, sum(total) as total
from return
group by pcode
) r
on r.pcode = pl.pcode
ORDER BY total ASC;
你的错误是什么?什么是ff?并且考虑提供一个SqLoDeld.“FF”意思是“跟随”,即使没有正式的歧义,我总是发现使用混乱!嘿,我是个诗人。。。