简体   繁体   中英

how to insert auto_increment

If i've the following database

CREATE TABLE `my_table` (
  `year` text,
  `event` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `my_table` VALUES ('2011', 'john');
INSERT INTO `my_table` VALUES ('2011', 'dave');
INSERT INTO `my_table` VALUES ('2010', 'hany');

My question is how to add id auto_increment so that it can be

INSERT INTO `my_table` VALUES (1, '2011', 'john');
INSERT INTO `my_table` VALUES (2, '2011', 'dave');
INSERT INTO `my_table` VALUES (3, '2010', 'hany');

I've tired this but failed

$q1 = "ALTER TABLE `my_table` ADD COLUMN `id` int(3) NOT NULL auto_increment";
mysql_query($q1) or die(mysql_error()." at row ".__LINE__);

and given me error Incorrect table definition so how to do it correctly.

you should add first the COLUMN then INDEX and then AUTO_INCREMENT

ALTER TABLE  `my_table` ADD COLUMN `id` int(3) NOT NULL;
ALTER TABLE  `my_table` ADD PRIMARY KEY (`id`);
ALTER TABLE  `my_table` CHANGE  `id`  `id` INT( 3 ) NOT NULL AUTO_INCREMENT;

OR 2 queries:

ALTER TABLE my_table ADD COLUMN `id` int (3) NOT NULL;
ALTER TABLE my_table ADD PRIMARY KEY `id`(`id`), CHANGE  `id`  `id` INT( 3 ) NOT NULL 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