2011-01-25 140 views
14

我有一個奇怪的問題與MySQL。Mysql - 將auto_increment添加到主鍵

我想改變一個表的列,這是一個主鍵,並有一個auto_increment約束定義它。這也是多個其他表的外鍵引用。 我需要在父級和所有子級中更改此列的長度。

set foreign_key_checks=0; 
alter table Parent modify Identifier smallint(10) unsigned; 
alter table Child_1 modify FK_Identifier smallint(10) unsigned; 
alter table Child_2 modify FK_Identifier smallint(10) unsigned; 
alter table Child_3 modify FK_Identifier smallint(10) unsigned; 
alter table Child_4 modify FK_Identifier smallint(10) unsigned; 
alter table Child_5 modify FK_Identifier smallint(10) unsigned; 
set foreign_key_checks=1; 

這將刪除父表上的自動增量。什麼是最好的方式來添加約束回來?

以下似乎失敗。

mysql> ALTER TABLE Parent MODIFY Identifier smallint(10) PRIMARY KEY AUTO_INCREMENT; 
ERROR 1068 (42000): Multiple primary key defined 


ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT; 
------------------------ 
LATEST FOREIGN KEY ERROR 
------------------------ 
110125 15:49:08 Error in foreign key constraint of table db/Child_1: 
there is no index in referenced table which would contain 
the columns as the first columns, or the data types in the 
referenced table do not match to the ones in table. Constraint: 
, 
    CONSTRAINT Child_1_ibfk_1 FOREIGN KEY (FK_Identifier) REFERENCES RoomProfile (Identifier) ON DELETE CASCADE ON UPDATE CASCADE 
The index in the foreign key in table is PRIMARY 

有沒有更好的方法來實現這個目標?

編輯:展會打造爲(後ALTER):

CREATE TABLE `Parent` (
    `Identifier` smallint(10) unsigned NOT NULL default '0', 
    `Name` varchar(20) default NULL, 
    `Description` varchar(100) default NULL, 
    PRIMARY KEY (`Identifier`), 
    UNIQUE KEY `Name` (`Name`), 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 | 

之前可以修改

`Identifier` smallint(5) unsigned NOT NULL AUTO_INCREMENT, 

謝謝!

+0

您可以發佈SHOW的'結果CREATE TABLE Parent' – Mchl

回答

30

你不需要在修改語句指定PRIMARY KEY

ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT; 
+0

我已經更新具有相同的結果後。 –

+2

嘗試在運行時禁用'foreign_key_checks'。 – Mchl

+0

set set foreign_key_checks = 0;並運行上述不起作用。 :( –