Waiting for table metadata lock mysql出现此错误解决办法

出现这种情况的说明,我是需要去修改表的结构,但是一修改,就直接卡死,然后就会报 Waiting for table metadata lock 这个错. 实际上,这个错不止是修改表结构会出现,你对这张表的任务锁表操作,都将不能实现.

解决方法

一 : 首先排除所有的长事物,慢查询等阻塞ddl,这类操作,会阻塞后续的操作

使用 show processlist 可以看到 一个列表 ,在这个列表里面有个字段info 就是当前阻塞的长事物的sql语句, 如果发现有这样的语音,kill掉 id即可
在这里插入图片描述

如图,为了演示,我使用了 一句sql (select sleep(30) ) 来模拟阻塞…

假设是这条sql是 造成阻塞的元凶,那么执行
kill 47660 ;
即可释放

二: 再排除 未提交的事物 ,这类也会阻塞ddl ,阻塞后续操作
刚才通过 show processlist 命令没有任务正在阻塞的操作,但是,实际上有 未提交的事物存在.这就需要去information_schema.innodb_trx 的这个表中去查看了.
使用 这个sql 命令 进行查看, 需要root用户或者足够的权限才能查看.

SELECT * FROM information_schema.innodb_trx

如果这个sql能查询出结果,如图 :
在这里插入图片描述

则是有阻塞了…
执行kill 命令即可强制释放掉对应的线程
如: kill 47660

根据官方的解释这个操作是
官方手册上对此的说明如下:
If the server acquires metadata locks for a statement that is syntactically valid but fails during execution, it does not release the locks early. Lock release is still deferred to the end of the transaction because the failed statement is written to the binary log and the locks protect log consistency.
也就是说除了语法错误,其他错误语句获取到的锁在这个事务提交或回滚之前,仍然不会释放掉。because the failed statement is written to the binary log and the locks protect log consistency 但是解释这一行为的原因很难理解,因为错误的语句根本不会被记录到二进制日志。

扫描二维码关注公众号,回复: 9005267 查看本文章

处理方法:通过performance_schema.events_statements_current找到其sid, kill 掉该session. 也可以 kill 掉DDL所在的session.

下面,还原下这个情况出现的情况 :
begin;
select * from

; table 必须是存在的表名
就是这样,开启事物,但是不提交…
再去执行 SELECT * FROM information_schema.innodb_trx 就会看到阻塞的线程id…

三 执行失败的sql操作

通常这种很难遇到,第一种和第二种比较常见 如果上面两种都没有,那么可能就是在一个显示的事务中,对TableA进行了一个失败的操作(比如查询了一个不存在的字段),这时事务没有开始,但是失败语句获取到的锁依然有效,没有释放。从performance_schema.events_statements_current表中可以查到失败的语句。

官方手册上对此的说明如下:
If the server acquires metadata locks for a statement that is syntactically valid but fails during execution, it does not release the locks early. Lock release is still deferred to the end of the transaction because the failed statement is written to the binary log and the locks protect log consistency.
也就是说除了语法错误,其他错误语句获取到的锁在这个事务提交或回滚之前,仍然不会释放掉。because the failed statement is written to the binary log and the locks protect log consistency 但是解释这一行为的原因很难理解,因为错误的语句根本不会被记录到二进制日志。
处理方法:通过performance_schema.events_statements_current找到其sid, kill 掉该session. 也可以 kill 掉DDL所在的session.

修改表结构,是危险的操作,操作前,最好确认没有这些事物,确保修改表时能获取到独占锁,不然,会操作整个系统对这个表的操作,全部阻塞…然后最好设置通过lock_wait_timeout设置好超时时间,避免长时间的metedata锁等待。

发布了98 篇原创文章 · 获赞 70 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/u012930316/article/details/100734610
今日推荐