문제

I have just managed to migrate a pretty big database from SQL Server to MySQL. I didn't set the primary keys to auto increment during the migration because the tables have relationships based on ids as primary keys which are foreign keys in another table.

Now for adding new records I want to alter the primary key 'id' columns in all tables to be autoincrement but starting from the last highest number in the id column in each table.

What's the best way to do this without losing the relationships I already have?

UPDATE: Trying to add autoincrement gives me this error:

ERROR 1067: Invalid default value for 'id'

SQL Statement:

ALTER TABLE `skandium`.`brands` CHANGE COLUMN `id` `id` INT(11) NOT NULL DEFAULT '0' AUTO_INCREMENT

ERROR 1050: Table 'brands' already exists

SQL Statement:

CREATE TABLE `brands` (
  `id` int(11) NOT NULL DEFAULT '0',
  `brand` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
도움이 되었습니까?

해결책

Just add the auto-increment on your needed columns. It won't affect existing rows. It will start with the next available value.

Note that a column being auto-increment means just that if you don't assign a value to it one will be added by MySQL. If you want to supply explicit values you can do so without anything special happening. So you could have set those columns to auto-increment right from the start.

A column with auto-increment cannot have an explicit default value.

Tested

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top