mySQL上的重复密钥多次更新

时间:2012-07-24 18:04:14

标签: php mysql sql

我试图创建一个简单的SQL INSERT否则UPDATE语句,但说实话我不知道我在做什么

这是我到目前为止的功能

function addInventoryBook($isbn, $sku, $price, $quantity, $condition, $dateOpened){
   $q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price, 
   $quantity, '$condition', $dateOpened)
   ON DUPLICATE KEY UPDATE VALUES('$isbn', '$sku', $price, $quantity, 
   '$condition', $dateOpened)";     

   return mysql_query($q, $this->connection);           
}

以前的功能似乎更新价格字段正在运作

function addInventoryBook($isbn, $sku, $price, $quantity, $condition, $dateOpened){
   $q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price, 
   $quantity, '$condition', $dateOpened)
   ON DUPLICATE KEY UPDATE price = $price";     

   return mysql_query($q, $this->connection);           
}

2 个答案:

答案 0 :(得分:5)

我会这样写,而不是第二次提供每个值:

ON DUPLICATE KEY UPDATE 
  isbn       = VALUES(isbn)
  sku        = VALUES(sku)
  price      = VALUES(price)
  quantity   = VALUES(quantity)
  condition  = VALUES(condition)
  dateOpened = VALUES(dateOpened)

(如果插入成功,那将分配已经插入的值。)

(您可能不希望将值分配给构成插入所违反的“唯一”键的任何列;我已在此处包含所有列,因为这是您在尝试中显示的内容。)

答案 1 :(得分:2)

Assuimg TBL_INVENTORY是一个包含列值的字符串:

$q = "INSERT INTO ".TBL_INVENTORY." VALUES('$isbn', '$sku', $price,     $quantity, '$condition', $dateOpened) ON DUPLICATE KEY UPDATE isbn='$isbn', sku='$sku', price='$price', quantity='$quantity', condition='$condition', dateOpened='$dateOpened'";

参考链接:http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html