简体   繁体   English

在类似条件下对不同表和列进行更新

[英]UPDATE on different tables and columns by similar condition

I have to run a procedure which will update an old value with the new value across several tables. 我必须运行一个过程,该过程将在多个表中用新值更新旧值。 All those tables are different and have different column name, and also they could not even have matching $old_value in them (in this case columns should not be updated), so only thing I could think of is to run a transaction, like this: 所有这些表都是不同的,并且具有不同的列名,而且它们甚至都没有匹配的$old_value (在这种情况下,列不应更新),所以我唯一想到的就是运行事务,如下所示:

$new_value = 'something';

$DBH->prepare("SELECT old_value FROM table_0 WHERE id = :id");
$DBH->execute(':id' => $some_value);
$result = $DBH->fetch(PDO::FETCH_ASSOC);

if( $new_value != $result[0]['old_value'] )
{
    $DBH->beginTransaction();

    $DBH->exec("UPDATE table_1 SET column_1 = $new_value WHERE column_1 = $old_value");
    $DBH->exec("UPDATE table_2 SET column_2 = $new_value WHERE column_2 = $old_value");
    $DBH->exec("UPDATE table_2 SET column_3 = $new_value WHERE column_3 = $old_value");

    $DBH->rollBack();
}

Is there any better solution? 有更好的解决方案吗? Maybe way to run UPDATE on SELECT without affecting whole result set? 也许可以在不影响整个结果集的情况下在SELECT上运行UPDATE的方法?

You have three different update conditions there, so you basically need three different updates. 您在那里有三个不同的更新条件,因此您基本上需要三个不同的更新。 Enclosing them inside a transaction as you've done is the best way to do that reliably. 完成后将它们包含在事务中是可靠地执行此操作的最佳方法。

At the end you need to do 最后你需要做

$DBH->commit();

You do $DBH->rollback() only if you got an error. 仅在出现错误时才执行$DBH->rollback() Rollback undos everything you have done since the start of the transaction. 回滚将撤消自事务开始以来您所做的一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM