How to add auto_increment field to a table with huge data?

jia Jimmy :

Say there's a table table_test, and there're about 10M rows data in the table. And I want to add a auto_increment field like key to do some pagination work. What is the best way to make it work?

the table stucture as below:

# table_test

+---------------------------------------+--------------+------+-----+---------+-------+
| Field                                 | Type         | Null | Key | Default | Extra |
+---------------------------------------+--------------+------+-----+---------+-------+
| ad_id                                 | int(64)      | NO   | PRI | NULL    |       |
| account_id                            | varchar(64)  | YES  | MUL | NULL    |       |
| country                               | varchar(64)  | NO   | PRI | NULL    |       |
| image_hash                            | varchar(64)  | YES  |     | NULL    |       |
+---------------------------------------+--------------+------+-----+---------+-------+



| table_test | CREATE TABLE `table_test` (
  `ad_id` int(11) NOT NULL,
  `account_id` varchar(64) DEFAULT NULL,
  `country` varchar(64) NOT NULL,
  `image_hash` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`,`country`),
  KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

update:

change id to ad_id, and ad_id here is unique key togather with field country, so ad_id itself may be duplicated.

Nae :

I'd go:

-- drop PK as AUTO increment demands being the PK
ALTER TABLE table_test DROP PRIMARY KEY;
-- add Id as PK and the first column
ALTER TABLE table_test ADD Id INT AUTO_INCREMENT PRIMARY KEY FIRST;
-- make sure the old PK is unique
ALTER TABLE table_test ADD CONSTRAINT table_test_uk UNIQUE (ad_id, country);

or perhaps:

CREATE TABLE table_test2 LIKE table_test;
ALTER TABLE table_test2 DROP PRIMARY KEY;
-- add Id as PK and the first column
ALTER TABLE table_test2 ADD Id INT AUTO_INCREMENT PRIMARY KEY FIRST;
-- make sure the old PK is unique
ALTER TABLE table_test2 ADD CONSTRAINT table_test2_uk UNIQUE (ad_id, country);
INSERT INTO table_test2(ad_id, account_id, country, image_hash)
SELECT ad_id, account_id, country, image_hash FROM table_test;
DROP TABLE table_test;
RENAME TABLE table_test2 TO table_test;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170151&siteId=1