如果存在更新与另一个表的列的总和插入

时间:2014-01-13 09:36:02

标签: mysql sql-update duplicates

我尝试使用此代码更新记录(如果存在),如果不存在则插入 我有三个表Products,Products_Sold和Products_Purchased

$ ProductID = $ _POST [“ProductID”]; (来自html表格)

       <?php
   include "insert.php";
   $con = mysqli_connect("localhost", "root", "pswd", "Inventory");
  // Check connection
   if (!$con) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con, "Inventory");

  $ProductID = $_POST['ProductID'];
  $ProductName = $_POST['ProductName'];
   $UnitPrice = $_POST['UnitPrice'];
   $SellingPrice= $_POST['SellingPrice'];
   $Quantity = $_POST['Quantity'];
   $PurchaseDate = date('Y-m-d',strtotime($_POST['PurchaseDate']));
   $TotalPrice= $UnitPrice * $Quantity;

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

mysqli_query($con,$sql);
mysqli_close();
?>

我使用的是mysql 5.5.34-0ubuntu0.12.04.1(Ubuntu)

有人可以帮我解决这个问题吗?

0 个答案:

没有答案