将SUM()添加到mySQL JOIN查询中

时间:2011-12-09 15:17:27

标签: php mysql join sum

我想将两个数据库连接在一起,并计算两个表中相同ID的每个数据库的总和,如果你得到的话来自......

我有一个ID为product_name,product_description的数据库 另一个有ID,库存金额,date_added

我使用JOIN函数将数据库连接在一起并正确显示它们,但是对于数据库中的每个条目,当我添加股票并在前端显示另一行时,它会添加另一行。我希望将所有相同的id组合成一行。

我试过这个:

$result = mysql_query("SELECT * FROM site_products JOIN site_trans ON site_products.product_id = site_trans.trans_product GROUP BY site_products.product_id");

它将同一个ID组合成一行,但库存量只显示最后添加的金额,而不是总金额。

我正在考虑将SUM()添加到此,但我不确定它在查询中的位置。

3 个答案:

答案 0 :(得分:0)

来自sqlcourse2.com

The GROUP BY clause will gather all of the rows together that contain data in the
specified column(s) and will allow aggregate functions to be performed on the 
one or more columns.

您可以在以下链接中阅读有关使用聚合函数用途的GROUP BY的更多信息:

现在我认为理解以下解决问题的查询会很简单:

SELECT 
    site_products.product_id, 
    SUM(stock amount) AS total_amount
    FROM site_products JOIN site_trans 
            ON site_products.product_id = site_trans.trans_product 
    GROUP BY site_products.product_id

答案 1 :(得分:0)

SELECT site_products.*, SUM(site_trans.stock_amount) AS total_stock FROM site_products JOIN site_trans ON (site_products.product_id = site_trans.trans_product) GROUP BY site_products.product_id

答案 2 :(得分:0)

这应该有效:

 $result = mysql_query("SELECT site_products.Id, site_products.product_name, site_products.product_description, SUM(site_trans.stockamount) FROM site_products JOIN site_trans ON site_products.product_id = site_trans.trans_product GROUP BY site_products.product_id, site_products.product_name, site_products.product_description");