从两个不同的表中减去

时间:2013-09-03 15:45:55

标签: php mysql

我有3个表格“产品列表,销售,退货”,所以我要举例说明我有3个销售和2个退货,如下所示。

这是产品清单中的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  |  10

这是来自返回的ff数据

id | pcode | total | lose
 3 |  222  |  200  |  10
 4 |  222  |  100  |  10

我的问题是这个。我想从产品列表中选择数据,并且总和来自销售额的“总计”和“利润”值,并将来自退货的“总计”和“损失”值相加。然后减去我的两个表来获得结果。预期结果必须是这样的。

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");

2 个答案:

答案 0 :(得分:1)

您似乎尝试使用AND加入两个表,这不太正确;)

试试这个:

...
LEFT JOIN `sales` USING (`pcode`)
LEFT JOIN `return` USING (`pcode`)
...

我不完全确定这会有用,可能会抱怨column `pcode` is ambiguous。如果发生这种情况,请尝试这样做:

...
LEFT JOIN `sales` ON `sales`.`pcode` = `productlist`.`pcode`
LEFT JOIN `return` ON `return`.`pcode` = `productlist`.`pcode`
...

答案 1 :(得分:0)

您的查询结构不会返回正确的结果。无论您如何修复语法,您仍然会在给定产品的销售和退货之间获得笛卡尔积。

一个解决方法是在连接之前进行聚合:

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;