2012-01-26 82 views
12

我想將數據庫中某些主鍵列的數據類型從INT更改爲BIGINT。下面的定義是一個玩具的例子來說明這個問題:mysql alter int column to bigint with foreign keys

CREATE TABLE IF NOT EXISTS `owner` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `thing_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `thing_id` (`thing_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 

DROP TABLE IF EXISTS `thing`; 
CREATE TABLE IF NOT EXISTS `thing` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 

ALTER TABLE `owner` 
    ADD CONSTRAINT `owner_ibfk_1` FOREIGN KEY (`thing_id`) REFERENCES `thing` (`id`); 

現在,當我嘗試EXECUT以下命令之一:

ALTER TABLE `thing` CHANGE `id` `id` BIGINT NOT NULL AUTO_INCREMENT; 
ALTER TABLE `owner` CHANGE `thing_id` `thing_id` BIGINT NOT NULL; 

我遇到一個錯誤

#1025 - Error on rename of './debug/#[temp-name]' to './debug/[tablename]' (errno: 150) 

SHOW INODB STATUS輸出:

LATEST FOREIGN KEY ERROR 
------------------------ 
120126 13:34:03 Error in foreign key constraint of table debug/owner: 
there is no index in the table which would contain 
the columns as the first columns, or the data types in the 
table do not match the ones in the referenced table 
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint: 
, 
CONSTRAINT "owner_ibfk_1" FOREIGN KEY ("thing_id") REFERENCES "thing" ("id") 

我猜測外鍵定義塊會改變任何一邊的列類型。解決這個問題的簡單方法是刪除外鍵定義,修改列並重新定義外鍵。有更好的解決方案嗎?

+1

你提到的方法並不幼稚,你可以真正使用它。 – Devart

+0

謝謝Devart!我一直在尋找一個不那麼痛苦的解決方案,因爲我必須在很多表格上使用它,但顯然要刪除並重新創建約束似乎是一種方法: - /。 – deif

回答

7

即使使用SET foreign_key_checks = 0,也不能更改約束列的類型。 從MySQL文檔:http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

However, even if foreign_key_checks = 0, InnoDB does not permit the creation of a foreign key constraint where a column references a nonmatching column type.

所以,我同意Devart的評論。只需放下並重新創建即可。

+0

也嘗試禁用外鍵檢查,它不起作用。謝謝指出原因。 – deif

3

我可以建議你重命名GUI工具等領域 - dbForge Studio for MySQL(免費試用版):

只需選擇要在數據庫資源管理器來重命名字段中,單擊Refactoring->重命名命令,輸入新在打開的窗口中輸入名稱,然後按OK,它將重命名該字段並自動重新創建所有外鍵。

0

我也有類似問題的解決方案是變化的條款:

ALTER TABLE table_name CHANGE id id BIGINT(20) NOT NULL AUTO_INCREMENT; 

爲我工作。