首先需要了解什么是死锁:当多个事务同时申请某个资源(如行、表等)时,而每个事务又持有其他事务需要的资源,就会发生死锁。这时,任何一方都无法继续执行下去,只能等待其他事务释放资源。
SHOW ENGINE INNODB STATUS\G
以上语句可以查看当前数据库的状态,包括死锁的信息。运行这条语句,会看到类似下面的输出:
===================================== 2021-05-13 14:11:28 7fb01e81e700 INNODB MONITOR OUTPUT ===================================== Per second averages calculated from the last 5 seconds ----------------- ... ----------------- LATEST DETECTED DEADLOCK ------------------------ 2021-05-13 13:12:18 7fb01bced700 *** (1) TRANSACTION: TRANSACTION 4281271323, ACTIVE 0 sec starting index read mysql tables in use 1, locked 1 LOCK WAIT 2 lock struct(s), heap size 360, 1 row lock(s) MySQL thread id 12, OS thread handle 0x7fb01c04e700, query id 188 localhost root updating UPDATE test SET price = 100 WHERE id = 1 *** (1) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 1401 page no 4 n bits 72 index `PRIMARY` of table `test` trx id 4281271323 lock_mode X locks rec but not gap waiting Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0 ... ------------------------- LATEST FOREIGN KEY ERROR ------------------------- 2021-05-13 14:11:25 7fb01e81e700 Transaction: TRANSACTION 0, ACTIVE 11 sec inserting mysql tables in use 1, locked 1 9 lock struct(s), heap size 2936, 11 row lock(s), undo log entries 11 MySQL thread id 11, OS thread handle 0x7fb01bcef700, query id 202 localhost root update ...
其中的输出信息中,LATEST DETECTED DEADLOCK就是最近一次发现的死锁信息。在这段输出中,会显示当前的所有事务以及其所拥有的锁以及等待的锁。可以根据输出的信息,找出造成死锁的具体事务。
通过以上的方法,可以在MySQL数据库中查看死锁的详细信息并解决死锁问题。