选择3个不同的表格

时间:2013-09-03 07:35:19

标签: php mysql

我有3个名为rsalesrreturnproductlist的表格。表格rsalesrreturn包含total 。我的目标是,我想要汇总来自total表的rsalestotal值的所有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

我的问题是:我想对totalrsales表中的所有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");

1 个答案:

答案 0 :(得分:1)

你不清楚哪些不适合你。你得到的结果,但数字不是你所期望的?好吧,假设您有三个销售和两个退货,那么您通过加入所有表格获得六个记录。因此,您的销售额翻倍,回报增加三倍。

您可以为一个解决方案加入聚合:

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