0

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

这是产品列表中的 ff 数据

id | pcode | pname | pdesc | 
 1 |  222  | 33uf  | 10v   | 

这是来自sales的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");
4

2 回答 2

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`
...
于 2013-09-03T15:49:34.413 回答
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;
于 2013-09-03T15:59:42.020 回答