当我选择多行进行更新时,我可以死锁吗?

Dam*_*nJW 5 mysql database-deadlocks

在MySQL + InnoDB中,假设我有一个表,并且两个线程都执行“ SELECT ... FOR UPDATE”。假设两个SELECT语句最终都选择多行,例如它们两个最终都选择行R42和R99。这可能会陷入僵局吗?

我在想这种情况:第一个线程尝试锁定R42,然后锁定R99,第二个线程尝试锁定R99,然后锁定R42。如果我不走运,两个线程将陷入僵局。

我在MySQL 词汇表中读到了“死锁”

当事务锁定多个表中的行时(通过诸如UPDATE或SELECT ... FOR UPDATE之类的语句),但顺序相反,则会发生死锁。...

为了减少死锁的可能性,...在SELECT ... FOR UPDATE和UPDATE ... WHERE语句中使用的列上创建索引。

暗示在我的情况(单表)中,我不会死锁,可能是因为MySQL自动尝试按主键的顺序锁定行,但是我想确定一下,并且我无法在行中找到合适的位置。文档,告诉我确切的情况。

Gir*_*Rao 3

来自 MySQL 文档

\n\n
InnoDB uses automatic row-level locking. You can get deadlocks even in the case of \ntransactions that just insert or delete a single row. That is because these operations    \nare not really \xe2\x80\x9catomic\xe2\x80\x9d; they automatically set locks on the (possibly several) index \nrecords of the row inserted or deleted.\n
Run Code Online (Sandbox Code Playgroud)\n\n

http://dev.mysql.com/doc/refman/5.1/en/innodb-deadlocks.html

\n\n

所以一般情况下,死锁并不是致命的,你只需要再试一次,或者添加适当的索引,这样扫描的行数就会减少,从而锁定的行数也会减少。

\n