php - INSERT SET :id if row does not exist, UPDATE WHERE :id 否则

标签 php mysql

我有一个代码,如果指定的 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 like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE 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 a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.

关于php - INSERT SET :id if row does not exist, UPDATE WHERE :id 否则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17262612/

相关文章:

php - LinkedIn 获取 token 返回 HTTP 1.1 400 - 错误请求错误

php - 迁移后测试数据(HTML -> PHP -> SQL)

php - 使用 PHP 导出为 CSV 并显示超链接单元格

php - 通过 PHP 保存 png 时获取深色图像

php - 通过 post [文件上传] 将表单数据提交到 iframe

php - 通过键访问数组的值

mysql - rake db:seed 失败并显示错误消息 Mysql2::Error: 你的 SQL 语法有错误

php - 循环中的 SQL 查询累积每个循环

mysql - 为什么带括号和不带括号的 UNION ALL 的行为不同?

mysql - 如何使这个语法更好?