1

我有 3 个名为rsales, rreturn,的表productlist。表rsalesrreturntotal 。我的目标是,我想对表中的所有totalrsalestotal值求和,并仅从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");
4

1 回答 1

1

你对什么对你不起作用不是很明确。您是否获得了结果,但数字不是您所期望的?好吧,假设您有 3 次销售和 2 次退货,然后通过连接所有表获得 6 条记录。因此,您的销售额翻了一番,回报翻了三倍。

对于一种解决方案,您可以改为加入聚合:

$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");
于 2013-09-03T08:00:27.497 回答