我有3个表名为rsalesrreturnproductlist。表rsalesrreturntotal列。我的目标是,将total表中的所有rsales值和total表中的值相加,并仅从rreturn表中选择特定值。
例如,假设我有来自productlist表的数据:

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

productlist表中的数据:
id | total | pcode |
1  |  200  | 222   |
2  |  200  | 222   |

rsales表中的数据:
id | total | pcode |
1  |  50   | 222   |
2  |  20   | 222   |

输出必须如下:
   id | pcode | pname | pdesc | total
   1  |  222  | 33uf  |  10v  |  470

我的问题是:我想对rreturntotal表中的所有rsales值求和,并从rreturn中选择所有值。我有下面的代码,运行得很好。但它只能对productlist表中的总值求和,或者只能对单个表中的值求和。
$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");

最佳答案

你不是很清楚什么对你不起作用。你得到结果了吗,但数字不是你期望的那样?好吧,假设你有三个销售和两个退货,然后你通过加入所有表得到六个记录。因此,你的销售额增加了一倍,回报增加了三倍。
对于一个解决方案,您可以加入聚合:

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

09-08 02:00