简体   繁体   中英

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

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.

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;

只是改变你的桌子

ALTER TABLE table_test CHANGE id id INT(11) NOT NULL AUTO_INCREMENT;

You can already use the 'id' column as an auto increment (unless you are using UUID or some other strategy).

You can check the following answer on how to alter the table to add auto increment to a table: ALTER table - adding AUTOINCREMENT in MySQL

Edit: If you wish to add a new column that will be auto incremented , you can use the following: ALTER TABLE table_test ADD id INT AUTO_INCREMENT;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM