使用其他两个表更新表

时间:2014-01-16 05:09:41

标签: php mysql sql-update sum

我有三个表t1t2t3

我想要的是使用t1

更新表格t1.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' )

2 个答案:

答案 0 :(得分:0)

愿它有所帮助

UPDATE table1,table2 SET table1.column1 = (     SELECT SUM(         (SELECT常量FROM table3)+         (SELECT table2.sum_number *** WHERE table2.table2_id1 = table1.id)     ) ) WHERE table1.id = table2.table2_id1;

UPDATE table1 SET column1 = (SUM(table2{& table3} WHERE table2_id1 = id1) WHERE id1 = table2_id1

答案 1 :(得分: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