mysql使用外键将int更改为bigint

dei*_*eif 12 mysql int foreign-keys alter bigint

我想将数据库中某些主键列的数据类型从INT更改为BIGINT.以下定义是一个玩具示例来说明问题:

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`);
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试执行以下命令之一时:

ALTER TABLE `thing` CHANGE `id` `id` BIGINT NOT NULL AUTO_INCREMENT;
ALTER TABLE `owner` CHANGE `thing_id` `thing_id` BIGINT NOT NULL;
Run Code Online (Sandbox Code Playgroud)

我遇到了一个错误

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

显示INODB状态输出:

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")
Run Code Online (Sandbox Code Playgroud)

我猜测外键定义会阻止更改任一侧的列类型.解决此问题的天真方法是删除外键定义,更改列并重新定义外键.有更好的解决方案吗?

lqe*_*qez 7

即使使用SET foreign_key_checks = 0,也无法更改约束列的类型.来自MySQL doc: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的评论.只需将其删除并再次创建即可.