[英]adding SUM() to mySQL JOIN query
我想将2个数据库连接在一起,并从两个表中计算出具有相同ID的每个数据库的总和,如果您知道我来自哪里……
我有一个ID为product_name,product_description的数据库,另一个数据库为ID,库存量,date_add
我已经使用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()添加到此,但是我不确定它在查询中的位置。
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
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
这应该工作:
$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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.