简体   繁体   中英

Atomicity multiple MySQL subqueries in an INSERT/UPDATE query?

I am planning on writing the following query:

INSERT INTO summary (user_id, total_points, count_operations)
SELECT 
   15 AS user_id,
   (SELECT SUM(points) FROM operations WHERE user_id = 15) AS total_points,
   (SELECT COUNT(*) FROM operations WHERE user_id = 15) AS count_operations
ON DUPLICATE KEY UPDATE
total_points = VALUES(total_points), 
count_operations = VALUES(count_operations);

Is the whole statement atomic? ie does MySQL (with MyISAM engine) internally locks the operations table?

Is there a possibility that MySQL would execute the two subsqueries sequentially which could result in some cases (if a new operation is added within that timeframe) that the total_points and count_operations would be inconsistent?

MyISAM still uses table-level locks .

These storage engines avoid deadlocks by always requesting all needed locks at once at the beginning of a query and always locking the tables in the same order. The tradeoff is that this strategy reduces concurrency; other sessions that want to modify the table must wait until the current DML statement finishes.

So other processes that want to update the tables you're using have to wait until your transaction is finished. If it puts a read lock on the table "operations", all subsequent write locks go into a queue and wait.

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