dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

MySQL: InnoDB: 如何理解 “Record locks for nonmatching rows are released after MySQL has evaluated the WHERE condition” #107

Closed dushaoshuai closed 1 year ago

dushaoshuai commented 1 year ago

如何正确理解 MySQL InnoDB 文档中的这几句描述?(目标语句做了加黑处理)

Using READ COMMITTED has additional effects: For UPDATE or DELETE statements, InnoDB holds locks only for rows that it updates or deletes. Record locks for nonmatching rows are released after MySQL has evaluated the WHERE condition. This greatly reduces the probability of deadlocks, but they can still happen.^1

SELECT ... FOR UPDATE and SELECT ... FOR SHARE statements that use a unique index acquire locks for scanned rows, and release the locks for rows that do not qualify for inclusion in the result set (for example, if they do not meet the criteria given in the WHERE clause). However, in some cases, rows might not be unlocked immediately because the relationship between a result row and its original source is lost during query execution. For example, in a UNION, scanned (and locked) rows from a table might be inserted into a temporary table before evaluating whether they qualify for the result set. In this circumstance, the relationship of the rows in the temporary table to the rows in the original table is lost and the latter rows are not unlocked until the end of query execution.^2

There are also other effects of using the READ COMMITTED isolation level. Record locks for nonmatching rows are released after MySQL has evaluated the WHERE condition. For UPDATE statements, InnoDB does a “semi-consistent” read, such that it returns the latest committed version to MySQL so that MySQL can determine whether the row matches the WHERE condition of the UPDATE.^3