排查因全局读锁导致的阻塞,核心是定位持有锁的会话并分析其执行的语句。通过查询 performance_schema.data_lock_waits 表可以明确看到谁在等待锁,而 performance_schema.events_statements_current 则能揭示是谁在持有锁以及它正在执行什么操作。结合这些信息,你可以直接终止阻塞源或优化慢查询,从而解除锁状态。

performance_schema.data_lock_waits 如何定位阻塞链
该视图直接展示了锁等待关系,通过连接相关表即可找出阻塞源头。你需要关注 LOCKING_TRANSACTION_ID 字段,它指向了持有锁的事务ID,进而关联到具体的会话和SQL语句。

SELECT
wl.requesting_engine_transaction_id AS waiting_txn,
wl.locking_engine_transaction_id AS holding_txn,
c2.thread_id AS blocker_thread,
s2.current_statement AS blocker_sql
FROM performance_schema.data_lock_waits wl
JOIN performance_schema.threads t1 ON wl.requesting_thread_id = t1.thread_id
JOIN performance_schema.threads t2 ON wl.locking_thread_id = t2.thread_id
LEFT JOIN performance_schema.events_statements_current s1 ON t1.thread_id = s1.thread_id
LEFT JOIN performance_schema.events_statements_current s2 ON t2.thread_id = s2.thread_id;
information_schema.innodb_trx 如何识别长事务
全局读锁通常由长时间运行的事务引起,innodb_trx 表提供了事务持续时间、状态等关键信息。通过筛选 trx_state 为 LOCK WAIT 或 running 且运行时间较长的记录,可以快速锁定嫌疑对象。
安装、修复、更新或打包一个基于 Python 和 PyMySQL 实现的 Windows `mysql` 命令。适用于用户希望在 PowerShell/CMD 中输入 `mysql` 时重定向到 Python 实现、需要交互式输入 MySQL 连接信息、需要同步到当前用户本地 bin 目录,或需要将该能力封装成可公开复用的 Codex skill。

SELECT
trx_id,
trx_state,
trx_started,
trx_mysql_thread_id,
trx_query
FROM information_schema.innodb_trx
WHERE trx_state IN ('LOCK WAIT', 'RUNNING')
ORDER BY trx_started ASC;
如何安全地终止导致阻塞的会话
一旦确定了阻塞源线程ID,可以使用 KILL 命令终止该会话。但需注意,直接终止可能回滚大量未提交的数据,建议在业务低峰期或确认无重要数据丢失风险后执行。同时,应检查是否可以通过优化SQL或缩短事务范围来避免此类问题再次发生。










