Is it possible to add a autoincrement primary index column in full mysql table belated?

孤街醉人 提交于 2019-12-23 15:46:31

问题


Assuming this table with nearly 5 000 000 rows

CREATE TABLE `author2book` (
  `author_id` int(11) NOT NULL,
  `book_id` int(11) NOT NULL,
  KEY `author_id_INDEX` (`author_id`),
  KEY `paper_id_INDEX` (`book_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

is it possible to add a primary index column id with autoincrement as first place? I expect something like this:

CREATE TABLE `author2book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,  <<<<  This is what I try to achieve!
  `author_id` int(11) NOT NULL,
  `book_id` int(11) NOT NULL,
  KEY `author_id_INDEX` (`author_id`),
  KEY `paper_id_INDEX` (`book_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Is this possible?

Edit: I should mention, that I'd like the added column to be populated.


回答1:


You can use ALTER TABLE to add the column and index in one command. i.e.:

ALTER TABLE author2book ADD id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id);

See the MySQL docs for ALTER TABLE for more info.




回答2:


Create a new table with the structure you want and the auto-incrementing key, and then insert all of the records from this table into that new table... then drop (or rename) the original table, and rename the new table to the original name.

insert into newTable (author_id, book_id) 
select * from author2book

newTable will then contain your desired output.




回答3:


ALTER TABLE author2book
ADD COLUMN `id` int(11) NOT NULL FIRST;

Populate the id field manually (by a script maybe?), then:

ALTER TABLE author2book
MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY;


来源:https://stackoverflow.com/questions/6192652/is-it-possible-to-add-a-autoincrement-primary-index-column-in-full-mysql-table-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!