我有一个代码,如果指定的 id 不存在,则在数据库中创建一行,否则更新该行。它有点慢(它检查一行是否存在,然后插入/更新它),我想优化它。如何将整个事情整合到一个 SQL 查询中?我想我应该使用 INSERT ... ON DUPLICATE KEY UPDATE 但我不明白它是如何工作的。谢谢。
$objectExists = true;
try {
$object = new Object();
$object->loadFromDatabaseById($this->id, $dbh); // tries to load object from database, throws
// ExceptionNotFound if object with specified id does not exist
}
catch(ExceptionNotFound $e) {
$objectExists = false;
}
if($objectExists)
$sth = $dbh->prepare(
'UPDATE objects ' .
'SET property1 = :property1, ' .
'property2 = :property2, ' .
'property3 = :property3 ' .
'WHERE id = :id'
);
else
$sth = $dbh->prepare(
'INSERT INTO objects ' .
'SET id = :id, ' .
'property1 = :property1, ' .
'property2 = :property2, ' .
'property3 = :property3'
);
$sth->bindParam(':id', $this->id, \PDO::PARAM_INT);
$sth->bindParam(':property1', $this->property1, \PDO::PARAM_STR);
$sth->bindParam(':property2', $this->property2, \PDO::PARAM_STR);
$sth->bindParam(':property3', $this->property3, \PDO::PARAM_INT);
$sth->execute();
$this->id = (int)$this->id;
最佳答案
MySQL has a REPLACE
statement这正是您正在寻找的:
REPLACE
works exactly likeINSERT
, except that if an old row in the table has the same value as a new row for aPRIMARY KEY
or aUNIQUE
index, the old row is deleted before the new row is inserted.
不删除的替代方案是 INSERT ... ON DUPLICATE KEY UPDATE
statement :
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE
index orPRIMARY KEY
, MySQL performs anUPDATE
of the old row.
关于php - INSERT SET :id if row does not exist, UPDATE WHERE :id 否则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17262612/