If your table is quite large, it is best not to use the statement:
alter table goods add column 'id' int(10) unsigned primary KEY AUTO_INCREMENT;
because it copies all the data into a temporary table, modifies the table and then copies it back. Itβs better to do it manually. Rename your table:
rename table goods to goods_old;
create a new table with the primary key and all the necessary indexes:
create table goods ( id int(10) unsigned not null AUTO_INCREMENT ... other columns ... primary key (id) );
move all the data from the old table to the new one, disabling keys and indexes to speed up copying:
- USE IT FOR MYISAM TABLES:
SET UNIQUE_CHECKS=0; ALTER TABLE goods DISABLE KEYS; INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; ALTER TABLE goods ENABLE KEYS; SET UNIQUE_CHECKS=1;
OR
- Use this for InnoDB tables :
SET AUTOCOMMIT = 0; SET UNIQUE_CHECKS=0; SET FOREIGN_KEY_CHECKS=0; INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; COMMIT; SET AUTOCOMMIT = 1;
It takes 2000 seconds to add PK to a table with ~ 200 million rows.
Denis Makarskiy May 11 '15 at 8:35 2015-05-11 08:35
source share