MySQL very slow for alter table query

前端 未结 5 1867
梦谈多话
梦谈多话 2020-12-07 13:02

Why is it taking more than an hour to simply update this table to add a column? This table has 15M rows. It has 2 indexes and a single key primary key. The ALTER TABLE quer

5条回答
  •  星月不相逢
    2020-12-07 13:57

    For minimize locking up of the large table that I want to alter, I do the following:

    • Create a new empty table based on the existing table and alter this new empty table.
    • Do a mysqldump of the large table such that it has one complete insert statement per record in the large table (switches -c and --skip-extended-insert)
    • Import this mysqldump into a different (empty) database with the empty renamed large_table.
    • Take a mysqldump of this new rename table from the other database and import it into the original database
    • Rename large_table and large_table_new in the original database.

      mysql> create table DATABASE_NAME.LARGE_TABLE_NEW like DATABASE_NAME.LARGE_TABLE;
      mysql> alter table DATABASE_NAME.LARGE_TABLE_NEW add column NEW_COLUMN_NAME COL_DATA_TYPE(SIZE) default null;
      
      $ mysqldump -c --no-create-info --skip-extended-insert --no-create-db -u root -p DATABASE_NAME LARGE_TABLE > LARGE_TABLE.sql
      
      mysql> create table test.LARGE_TABLE like DATABASE_NAME.LARGE_TABLE;
      
      $ mysql -u root -p -D test < LARGE_TABLE.sql
      
      mysql> rename table test.LARGE_TABLE to test.LARGE_TABLE_NEW;
      
      $ mysqldump -c --no-create-info --skip-extended-insert --no-create-db -u root -p test LARGE_TABLE_NEW > LARGE_TABLE_NEW.sql
      
      $ mysql -u root -p -D DATABASE_NAME < LARGE_TABLE_NEW.sql
      
      mysql> rename table DATABASE_NAME.LARGE_TABLE to DATABASE_NAME.LARGE_TABLE_OLD, DATABASE_NAME.LARGE_TABLE_NEW to DATABASE_NAME.LARGE_TABLE;
      

提交回复
热议问题