ID相似的同一列的总和值

时间:2019-04-27 10:43:36

标签: mysqli

我正在尝试使用查询共享同一组产品的数量(如果不为零)。

这是一个使用PHP5.6和MySQL查询的网站。

数据库表产品

+-------------+-------------------+-------------------+
| products_id | products_quantity |  products_master  |
+-------------+-------------------+-------------------+
|      11     |         1         |       12          |   
|      12     |         5         |       12          |
|      13     |         2         |       12          |
|      14     |         7         |       0           |
|      15     |         9         |       0           |
+-------------+-------------------+-------------------+

预期结果

+-------------+-------------------+-------------------+
| products_id | products_quantity |  products_master  |
+-------------+-------------------+-------------------+
|      11     |         8         |       12          |   
|      12     |         8         |       12          |
|      13     |         8         |       12          |
|      14     |         7         |       0           |
|      15     |         9         |       0           |
+-------------+-------------------+-------------------+

我需要帮助编写此代码

$sql = "SELECT products_id, IF(products_master != 0, (missing code to sum quantity), products_quantity) AS products_quantity FROM products ORDER BY products_quantity";

products_master相同(如果不为零)的产品具有数量总和。

1 个答案:

答案 0 :(得分:0)

您可以在子查询中使用联接和组

select p.products_id, 
    case products_master when 0 then products_quantity else x.qty end
from products p
left join  (select products_master, sum(products_quantity) as qty 
       from Products group by products_master) x 
on p.products_master = x.products_master