听起来你需要做的就是使用交易.
您必须使用InnoDB表来使用事务(实际上,其他一些数据库引擎都有事务,但InnoDB最常用于MySQL).
在第一次更新之前发出“BEGIN TRANSACTION”查询.
如果任何查询失败,请发出“ROLLBACK”查询以撤消所有内容.
这真的很简单.
如果你决定要进行部分回滚(回到事务开始后的某个点),那么你可以使用“ROLLBACK TO SAVEPOINT savepoint_name”.您将不得不发出第一个“SAVEPOINT savepoint_name”查询.
例如,在PHP中
mysql_query("BEGIN TRANSACTION");
$result1 = mysql_query("UPDATE `tbl_groups` SET `user_id` = 5 WHERE `group_id` = 3");
if($result1 === false) {
mysql_query("ROLLBACK");
}
mysql_query("SAVEPOINT savepoint1");
$result2 = mysql_query("UPDATE `tbl_users` SET `group_id` = 3 WHERE `user_id` = 5");
if($result === false) {
ROLLBACK TO SAVEPOINT savepoint1;
}
// COMMIT saves the changes to the db, making them visible to other sessions
// if the ROLLBACK TO SAVEPOINT statement executed, then only changes up to that SAVEPOINT will be saved
// if no ROLLBACK statements were executed, then all changes will be saved (assuming no MySQL errors that cause implicit ROLLBACK)
mysql_query('COMMIT');