SQL从表总和中选择*并按ID分组

时间:2013-03-13 13:02:01

标签: 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               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"];
}

一个例子:如果我在2个仓库上有相同的代码,那么它只获得其中的1个,我想要的是按product_id对数量和组进行求和。

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

试试这个:

'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"];

答案 1 :(得分:0)

查询:

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

PHP:

$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"];
}

请记住,我们依赖于产品表中的代码和ID是唯一对的事实。