Php SQL从表sum和group by id中选择*
我需要一个小的帮助来分组和合计项目id的数量 来自数据库的数据:Php SQL从表sum和group by id中选择*,php,sql,Php,Sql,我需要一个小的帮助来分组和合计项目id的数量 来自数据库的数据: products id code name price 1 1234 Product name 12 2 1235 Product name 12 3 1236 Product name 12 warehouses_products product_id warehouse_id quantity 1 1
products
id code name price
1 1234 Product name 12
2 1235 Product name 12
3 1236 Product name 12
warehouses_products
product_id warehouse_id quantity
1 1 12
2 1 0
2 2 3
3 1 1
3 2 1
PHP获取数据
$db = new PDO('mysql:host=localhost;dbname=data2;charset=utf8', 'user2', 'Password');
foreach($db->query('SELECT * FROM products as pr INNER JOIN warehouses_products AS s ON (s.product_id = pr.id) group by pr.id') as $row) {
echo $row["code"] . ' ' . $row["quantity"];
}
举个例子:如果我在两个仓库上有相同的代码,这只能得到其中的一个,我想要的是按产品id对数量和组进行求和
感谢您的帮助。尝试以下方法:
'SELECT *, SUM(s.quantity) AS sum_quantity FROM products as pr INNER JOIN warehouses_products AS s ON (s.product_id = pr.id) group by pr.id'
在您的foreach
中:
echo $row["code"] . ' ' . $row["sum_quantity"];
查询:
PHP:
请记住,我们所依赖的事实是产品表中的代码和id是唯一的一对 谢谢@Prasanth,这就是解决方案。@Dario:在堆栈溢出中,我们接受答案来表示感谢:)
SELECT p.id, p.code, SUM(wp.quantity) as quantity
FROM products p
JOIN warehouses_products wp ON wp.product_id = p.id
GROUP BY p.id, p.code
$db = new PDO('mysql:host=localhost;dbname=data2;charset=utf8', 'user2', 'Password');
foreach($db->query('SELECT p.id, p.code, SUM(wp.quantity) as quantity FROM products p JOIN warehouses_products wp ON wp.product_id = p.id GROUP BY p.id, p.code') as $row) {
echo $row["code"] . ' ' . $row["quantity"];
}