问题
I have two tables in my scenario
table1, which has about 20 tuples
table2, which has about 3 million tuples
table2 has a foreign key referencing table1 "ID" column.
When I try to execute the following query:
ALTER TABLE table1 MODIFY vccolumn VARCHAR(1000);
It takes forever. Why is it taking that long? I have read that it should not, because it only has 20 tuples.
Is there any way to speed it up without having server downtime? Because the query is locking the table, also.
回答1:
I would guess the ALTER TABLE is waiting on a metadata lock, and it has not actually starting altering anything.
What is a metadata lock?
When you run any query like SELECT/INSERT/UPDATE/DELETE against a table, it must acquire a metadata lock. Those queries do not block each other. Any number of queries of that type can have a metadata lock.
But a DDL statement like CREATE/ALTER/DROP/TRUNCATE/RENAME or event CREATE TRIGGER or LOCK TABLES, must acquire an exclusive metadata lock. If any transaction still holds a metadata lock, the DDL statement waits.
You can demonstrate this. Open two terminal windows and open the mysql client in each window.
- Window 1:
CREATE TABLE foo ( id int primary key );
- Window 1:
START TRANSACTION;
Window 1:
SELECT * FROM foo;
-- it doesn't matter that the table has no dataWindow 2:
DROP TABLE foo;
-- notice it waitsWindow 1:
SHOW PROCESSLIST;
+-----+------+-----------+------+---------+------+---------------------------------+------------------+-----------+---------------+ | Id | User | Host | db | Command | Time | State | Info | Rows_sent | Rows_examined | +-----+------+-----------+------+---------+------+---------------------------------+------------------+-----------+---------------+ | 679 | root | localhost | test | Query | 0 | starting | show processlist | 0 | 0 | | 680 | root | localhost | test | Query | 4 | Waiting for table metadata lock | drop table foo | 0 | 0 | +-----+------+-----------+------+---------+------+---------------------------------+------------------+-----------+---------------+
You can see the drop table waiting for the table metadata lock. Just waiting. How long will it wait? Until the transaction in window 1 completes. Eventually it will time out after lock_wait_timeout
seconds (by default, this is set to 1 year).
Window 1:
COMMIT;
Window 2: Notice it stops waiting, and it immediately drops the table.
So what can you do? Make sure there are no long-running transactions blocking your ALTER TABLE. Even a transaction that ran a quick SELECT against your table earlier will hold its metadata lock until the transaction commits.
来源:https://stackoverflow.com/questions/59093998/mysql-alter-table-taking-long-in-small-table