如何logging所有等待表锁的MySQL查询?

我们正试图诊断MySQL 5.0的死锁问题。 目前所有的表都是MyISAM表,所以所有的锁都是表锁。 我们有一个很好的table_locks_waitedtable_locks_immediate比(低于1:1000),但在几分钟内,我们得到了一些死锁。 这只发生在亚马逊EC2上,而不是我们其他的服务器上。

有没有办法logging所有无法立即获取表锁的查询? 我们希望看到所有对table_locks_waited编号有贡献的查询。

在慢日志中,显示的一个字段是locking时间

这是一个包含两个查询logging的示例

 # Time: 110726 1:00:09 # User@Host: mysql[mysql] @ [10.64.100.208] # Query_time: 8 Lock_time: 0 Rows_sent: 0 Rows_examined: 852669 insert into rates_old select * from rates; # Time: 110726 1:30:56 # User@Host: mysql[mysql] @ [10.64.100.208] # Query_time: 50 Lock_time: 0 Rows_sent: 0 Rows_examined: 11015414 SET timestamp=1311661856; delete a.*, b.* from zillowDump a, zillowHistory b where a.loanRequestId=b.loanRequestId and a.addDate < date_sub(now(), INTERVAL 2 week); 

请注意Lock_time:字段。

警告

在MySQL 5.1+中,该字段出现在默认的mysql.slow_log表中

 mysql> show create table mysql.slow_log\G *************************** 1. row *************************** Table: slow_log Create Table: CREATE TABLE `slow_log` ( `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `user_host` mediumtext NOT NULL, `query_time` time NOT NULL, `lock_time` time NOT NULL, `rows_sent` int(11) NOT NULL, `rows_examined` int(11) NOT NULL, `db` varchar(512) NOT NULL, `last_insert_id` int(11) NOT NULL, `insert_id` int(11) NOT NULL, `server_id` int(10) unsigned NOT NULL, `sql_text` mediumtext NOT NULL ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log' 1 row in set (0.00 sec) 

无论哪种方式,您都可以获得任何查询的locking时间

尝试使用以下命令实时查看查询和locking:

 watch -n 0.5 'mysqladmin -u root -ppassword "processlist"' 

如果locking发生了一段时间,你应该清楚发生了什么事情。