mysql如何查看当前事务_mysql当前事务查询方法

7次阅读

通过 information_schema.innodb_trx 表可查看当前运行事务,结合 processlist 和 innodb_lock_waits 分析锁等待与阻塞,必要时启用 InnoDB 监控获取详细状态。

mysql 如何查看当前事务_mysql 当前事务查询方法

mysql 中查看当前正在运行的事务,可以帮助你诊断锁等待、长事务或性能问题。以下是一些常用的方法来查询当前事务状态。

查看当前正在运行的事务(InnoDB 引擎)

MySQL 的 InnoDB 存储引擎支持事务,可以通过 information_schema.innodb_trx 表查看当前所有活跃的事务。

执行以下sql 语句

select trx_id, trx_state, trx_started, trx_mysql_thread_id, trx_query, trx_operation_state, trx_isolation_level FROM information_schema.innodb_trxG

字段说明:

  • trx_id:事务 ID
  • trx_state:事务状态(如 RUNNING、LOCK WAIT)
  • trx_started:事务开始时间
  • trx_mysql_thread_id:对应的 线程ID,可用于关联 processlist
  • trx_query:当前正在执行的 SQL 语句
  • trx_isolation_level:事务隔离级别

结合线程信息查看完整上下文

你可以将 innodb_trxperformance_schema.threadsSHOW PROCESSLIST 结合使用,获取更完整的会话信息。

SELECT p.ID, p.USER, p.HOST, p.DB, p.COMMAND, p.TIME, p.STATE, t.trx_started, t.trx_query FROM information_schema.innodb_trx t JOIN information_schema.processlist p ON t.trx_mysql_thread_id = p.ID;

查看事务锁等待情况

如果怀疑有事务阻塞,可以查看锁信息:

SELECT r.trx_id waiting_trx_id, r.trx_mysql_thread_id waiting_thread, r.trx_query waiting_query, b.trx_id blocking_trx_id, b.trx_mysql_thread_id blocking_thread, b.trx_query blocking_query FROM information_schema.innodb_lock_waits w JOIN information_schema.innodb_trx b ON b.trx_id = w.blocking_trx_id JOIN information_schema.innodb_trx r ON r.trx_id = w.requesting_trx_id;

这个查询能显示哪些事务在等待,以及是被哪个事务阻塞的。

启用 InnoDB 监控查看更详细事务信息

如果需要更深入的调试,可以临时开启 InnoDB 标准监控:

CREATE table if NOT EXISTS mysql.innodb_monitor (a int) ENGINE=INNODB; SET GLOBAL innodb_status_output=ON; SET GLOBAL innodb_status_output_locks=ON;

然后通过 SHOW ENGINE INNODB STATUSG 查看详细的事务和锁信息。注意:仅用于诊断,生产环境不建议长期开启。

基本上就这些方法。日常排查用 information_schema.innodb_trx 配合 processlist 就够了,遇到锁问题再查innodb_lock_waits。不复杂但容易忽略细节,比如线程 ID 的对应关系。

站长
版权声明:本站原创文章,由 站长 2025-12-13发表,共计1567字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
1a44ec70fbfb7ca70432d56d3e5ef742
text=ZqhQzanResources