Home > database > Questions about mysql row locks for update, please the great god answers.
Questions about mysql row locks for update, please the great god answers.
Time:09-17
For one of the most classic inventory oversold, assume that a data that is the case,
Id, brand name, a list of inventory such structure
Id product_sku inventory
10 1 SKU - 1
Looked at under a lot of online blog said, a common way is to add pessimistic or optimistic locking, Implementation is about: the beginning and read lock: for update, other transactions can only be blocked waiting for the current transaction is committed, able to read lock on the row data Optimistic locking with a version number field, the update submit time analysis of the current affairs in the process, any other process to modify the current data, if changed the failure
My understanding is: Process a: Select the inventory from the table where id=1 for update; Find out the inventory; Then $inventory=9;
Update the set inventory=9 WHERE id=1; commit;
When the update is direct assignment, Join the update when the update directly set the inventory=inventory - 1, not just don't need to add the lock?
Because of the update statement itself is not exclusive lock?
The simplest way of direct: Process: the begin; Update the set inventory=inventory - 1 WHERE id=1;
Process 2: begin; Update the set inventory=inventory - 2 WHERE id=1;
Process at this time it is our update, there are exclusive lock lock line, process two direct blocking,
Wait for the process to a transaction is committed, releases the lock, 2 to execute process,
So don't have to solve problems of oversold? Why do you also need to use for update to achieve?
Not more simple to solve?
Great god solve,
CodePudding user response:
Requires the user to write explicit affairs, general business is a bit more complicated scenarios, you don't have to understand the key points,
Easy to understand with bank withdrawals, If you have a 1000 yuan deposit, then: A. on your mobile phone bank transfer of RMB 600, B. your girlfriend took your bank card, 600 yuan on an ATM withdrawals, A, B two operations, separate execution is no problem, but have A problem with implementation, Transaction, that is, in order to avoid this kind of question,
You imagine, I said above scenario, no transaction, can do it?