2016-02-12 270 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 ";