简体   繁体   中英

Please help me understanding MySQL InnoDB Transactions

I'm trying to understand the locking mechanisms for InnoDB.

Let's say i have the following PHP script:

mysql_query('BEGIN;');
$a=mysql_query('SELECT id, status FROM testtable WHERE id=123 LIMIT 1 FOR UPDATE;'); 
$res=mysql_fetch_assoc($a);
$b=somefunction($res['id']);
$c=someotherfunction($b);
mysql_query('UPDATE testtable SET status=1 WHERE id=123;');
mysql_query('COMMIT;');

inside somefunction() and someotherfunction() we'll do a lot of other queries from the same table, but also from other tables. It even selects other fields from testtable where id=123.

Do i get it right that within this session i can do whatever i want with id=123, but other sessions will wait for the lock to be released?

Because i use 'for update' in the first query, that's the only row in testtable which will be locked. Any other tables or rows selected/updated/inserted in the same session are left untouched (unlocked)?

What will happen if someotherfunction() selects and updates a different field on id=123? Is this possible? Does the lock stay?

I'm not sure about the locking part, but transactions are made to allow "all or nothing" on a group of queries.

For example, if you were to run the following two queries for a payment of some sort:

UPDATE customer SET credit=credit - 1 WHERE id=1;
INSERT INTO subscriptions VALUES (...);

If the INSERT query fails, the customer will have their credit decremented, but not get the subscription, for example.

By wrapping it in a transaction, if any part of the query fails, it goes back to being like it was before.

BEGIN;
UPDATE customer SET credit=credit - 1 WHERE id=1;
INSERT INTO subscriptions VALUES (...);
COMMIT;

Either both queries will succeed, or no change will be made on failure.

EDIT: I don't believe InnoDB will do any locking for you automatically, look up SELECT ... LOCK IN SHARE MODE and SELECT ... FOR UPDATE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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