2014-01-16 28 views
0

我有三個表t1t2t3使用其他兩個表的更新表

我要的是更新表t1t1.Quantity= sum(t2.quantity) - sum(t3.quantity) where id= $_POST['id']

如何寫入查詢這一點。

我試過這個..但它不工作。

INSERT INTO Products 
    (`ProductID`, `ProductName`, `TotalQuantity`, 
    `TotalPrice`, `DateOfLastupdate`) 
values 
    ('$ProductID', '$ProductName', '$Quantity', 
    '$TotalPrice', '$PurchaseDate') 
ON DUPLICATE KEY 
    UPDATE Products.TotalQuantity = 
    (select sum(Products_Purchased.Quantity) from Products_Purchased 
     where ProductID = '$ProductID') 
    - (select sum(Products_Sold.Quantity) from Products_Sold 
      where ProductID = '$ProductID') 
+0

如果記錄不存在,那麼就應該插入其他應更新..這就是爲什麼使用的重複鍵 – mona

回答

0

試試這個

update products t1, 
(select productid,sum(Products_Purchased.Quantity) as x from Products_Purchased 
    group by productid having ProductID = '$ProductID') t2, 
(select productid,sum(Products_Sold.Quantity) as y from Products_Sold 
    group by productid having ProductID = '$ProductID') t3 
set TotalQuantity=t2.x-t3.y where t1.ProductID = '$ProductID' 
     and t1.productid=t2.productid and t1.productid=t3.productid 
+0

插入IM,但我可以用同樣的語句插入重複鍵? – mona

+0

應該可以..只是嘗試在您的發展:D –

+0

我也試過這個在終端上,但這是行不通的。 – mona