mysql修改外键类型,mysql将int列更改为带有外键的bigint

I want to change the datatype of some primary-key columns in my database from INT to BIGINT. The following definition is a toy-example to illustrate the problem:

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`);

Now when i try to execut one of the following commands:

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

ALTER TABLE `owner` CHANGE `thing_id` `thing_id` BIGINT NOT NULL;

i'm running into an error

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

SHOW INODB STATUS outputs:

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")

I'm guessing that the foreign key definition blocks changing the column type on either side. The naive approach to solve this problem would be to delete the foreign key definitions, alter the columns and re-define the foreign keys. is there a better solution?

解决方案

Even with SET foreign_key_checks = 0, you can't alter the type of the constraint column.

From 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.

So, I agree with the comment of Devart. Just drop it and create it again.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值