如何检查先前的查询是否正确执行?

How to check if previous query was executed correctly?

我要从一个用户账户中减少资金并增加另一个用户账户,即从一个账户向另一个账户转账。 例如,我有这段代码,在 MySql:

START TRANSACTION;
UPDATE accounts
SET balance = (balance-100)
WHERE account_id = 2 AND balance>100;

--If the above query is succesfully then:
UPDATE accounts
SET balance = (balance+100)
WHERE account_id =1;

--How can I exec the commit only if everything is ok?
COMMIT;

只有余额>100才执行第一次查询

然而,只有当前面的查询减少了余额时,才应该执行第二个查询(即第二次更新)。我怎样才能自动检查这个?

此外还有 COMMIT;仅当前 2 个查询已完成其工作时才必须执行。

如何实施?

(我也在使用 PHP,但我认为使用 sql 可以轻松解决这个问题。我错了吗?)

将操作作为单个查询执行,而不是作为查询包执行:

UPDATE accounts t1
CROSS JOIN accounts t2
SET t1.balance = (t1.balance-100),
    t2.balance = (t2.balance+100)
WHERE t1.account_id = 2 AND t1.balance>100
  AND t2.balance_id = 1;

-- or

UPDATE accounts
SET balance = balance + CASE account_id WHEN 1 THEN 100
                                        WHEN 2 THEN -100 END
WHERE account_id IN (1,2);

而且您根本不需要交易。


您还可以检查先前查询更改的行数(实际上,在磁盘上,不是正式的),并在第二次查询中考虑此信息:

START TRANSACTION;

UPDATE accounts
SET balance = (balance-100)
WHERE account_id = 2 AND balance>100;

UPDATE accounts
SET balance = (balance+100)
WHERE account_id =1 
  AND ROW_COUNT();  -- check does a row was altered in previous statement
                    -- if not then this statement will not alter any row too

COMMIT;