mysql鎖的理解
Alocking read, anUPDATE
, or aDELETE
generally set record locks on every index record that is scanned in the processing of the SQL statement. It does not matter whether there areWHERE
conditions in the statement that would exclude the row.InnoDB
does not remember the exactWHERE
condition, but only knows which index ranges were scanned. The locks are normally
翻譯:鎖定讀、更新或刪除通常對SQL語句處理過程中掃描的每個索引記錄設定記錄鎖。語句中是否有排除該行的條件並不重要。InnoDB不記得確切的位置條件,但只知道哪個索引範圍被掃描。這些鎖通常是下一個鍵鎖,它們也會阻塞插入到記錄之前的“間隙”中。但是,可以顯式禁用間隙鎖定,這將導致不使用next-key鎖定。更多資訊,見14.7.1節“InnoDB鎖”。事務隔離級別也會影響設定的鎖;見14.7.2.1節“事務隔離級別”。
If a secondary index is used in a search and index record locks to be set are exclusive,InnoDB
also retrieves the corresponding clustered index records and sets locks on them.
翻譯:如果在搜尋中使用了一個二級索引,並且要設定的索引記錄鎖是排他的,InnoDB也會檢索相應的聚集索引記錄並對它們設定鎖。
If you have no indexes suitable for your statement and MySQL must scan the entire table to process the statement, every row of the table becomes locked, which in turn blocks all inserts by other users to the table. It is important to create good indexes so that your queries do not unnecessarily scan many rows.
翻譯:如果沒有適合語句的索引,MySQL必須掃描整個表來處理語句,那麼表的每一行都會被鎖定,從而阻塞其他使用者對錶的所有插入。建立良好的索引很重要,這樣您的查詢就不會掃描很多行。
InnoDB
sets specific types of locks as follows.
SELECT ... FROM
is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set toSERIALIZABLE
. ForSERIALIZABLE
level, the search sets shared next-key locks on the index records it encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.
翻譯:SELECT ... FROM
是一致讀取,讀取資料庫的快照並且不設定鎖,除非事務隔離級別設定為SERIALIZABLE。對於SERIALIZABLE事務隔離級別,搜尋在遇到的索引記錄上設定共享的next-key鎖。但是,對於使用惟一索引來搜尋惟一行來鎖定行的語句,只需要一個索引記錄鎖。
ForSELECT ... FOR UPDATE
orSELECT ... LOCK IN SHARE MODE
, locks are acquired for scanned rows, and expected to be released for rows that do not qualify for inclusion in the result set (for example, if they do not meet the criteria given in theWHERE
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 aUNION
, scanned (and locked) rows from a table might be inserted into a temporary table before evaluation 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.
翻譯:SELECT ... FOR UPDATE
或SELECT ... LOCK IN SHARE MODE
下,對被掃描的行獲取鎖,對不符合結果集中包含條件的行釋放鎖(例如,如果它們不滿足WHERE子句中給出的條件)。但是,在某些情況下,可能不會立即解鎖行,因為在查詢執行期間,結果行與其原始資料來源之間的關係丟失了。例如,在一個聯盟,從表掃描(鎖)行可能會插入到臨時表之前評估他們是否有資格獲得結果集。在這種情況下,臨時表中的行之間的關係中的行原始表丟失,後者才行解鎖查詢執行的結束。