2016-02-12 269 views
0

我的数据库结构看起来财产以后像下面加入两行的值,并将它们合并成一个单一行MYSQL

customer_idproduct_idquantity

38    43   1 

36    34   1 

41    46   1 

41    46   1 

41    31   1 

如果数据库有两个product_ids与相同相同的值customer_id然后quantity必须被添加和行必须被合并为单行。

在上述情况下,customer_id 41有两个product_id,值为46.所以需要添加这两行的quantity,并且必须将两行合并为单行。

我尝试下面的代码,但它并不能帮助我

$sql3 = "select customer_id,product_id from oc_cart where customer_id  = '41'"; 
$products=mysql_query($sql3); 
while($rows=mysql_fetch_array($products)){ 
$cust_id = $rows['customer_id']; 
$prod_id = $rows['product_id']; 
} 
$sql4 = "select count(*) from oc_cart where customer_id =41 group by product_id "; 
$count=mysql_query($sql4); 

任何帮助将是非常greatfull。

谢谢。

+0

'选择CUSTOMER_ID,SUM(数量)从oc_cart组 –

回答

0

需要使用的MySQL函数SUM:由customer_id`

$sql4 = "select count(*), SUM(quantity) from oc_cart where customer_id =41 group by product_id ";