DELIMITER ;; CREATEPROCEDURE idata() BEGIN DECLARE i INT; SET i=1; WHILE (i<=100000) DO INSERTINTO t VALUES (i,i); SET i=i+1; END WHILE; END;; DELIMITER ;
CALL idata();
查询长时间等待
大概率是表t被锁住了,通过SHOW PROCESSLIST;查看语句处于什么状态
1
SELECT*FROM t WHERE id=1;
等MDL
执行时序
session A
session B
LOCK TABLE t WRITE;
SELECT * FROM t WHERE id=1;
session A通过LOCK TABLE命令持有表t的MDL写锁
session B执行DML,需要先持有表t的MDL读锁,从而进入阻塞状态
语句状态
session B的线程ID为33,状态为等待MDL:Waiting for table metadata lock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
mysql>SHOW PROCESSLIST; +----+-----------------+-----------+------+---------+-------+---------------------------------+----------------------------+ | Id |User| Host | db | Command |Time| State | Info | +----+-----------------+-----------+------+---------+-------+---------------------------------+----------------------------+ |4| event_scheduler | localhost |NULL| Daemon |21668| Waiting onempty queue |NULL| |30| root | localhost | test | Query |33| Waiting fortable metadata lock |SELECT*FROM t WHERE id=1| |31| root | localhost | test | Sleep |41||NULL| |33| root | localhost |NULL| Query |0| starting |SHOW PROCESSLIST | +----+-----------------+-----------+------+---------+-------+---------------------------------+----------------------------+
-- Closes all open tables, forces all tables in use to be closed, and flushes the prepared statement cache. FLUSH TABLES t WITH READ LOCK; FLUSH TABLES WITH READ LOCK;
DELIMITER ;; CREATEPROCEDURE udata() BEGIN DECLARE i INT; SET i=1; WHILE (i<=1000000) DO UPDATE t SET c=c+1WHERE id=1; SET i=i+1; END WHILE; END;; DELIMITER ;
执行时序
时刻
session A
session B
T1
START TRANSACTION WITH CONSISTENT SNAPSHOT;
T2
SELECT * FROM t WHERE id=1;(返回1,很慢)
T3
CALL udata();
T4
SELECT * FROM t WHERE id=1;(返回1,较慢)
T5
SELECT * FROM t WHERE id=1 LOCK IN SHARE MODE;(返回1,000,001,很快)
执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
-- T4时刻,快照读(一致性读) mysql>SELECT*FROM t WHERE id=1; +----+------+ | id | c | +----+------+ |1|1| +----+------+ 1rowinset (0.99 sec)
-- T5时刻,当前读 mysql>SELECT*FROM t WHERE id=1 LOCK IN SHARE MODE; +----+---------+ | id | c | +----+---------+ |1|1000001| +----+---------+ 1rowinset (0.00 sec)