Change Primary Key from BigInt to Unsigned BigInt when linked as foreign key

♀尐吖头ヾ 提交于 2019-12-12 03:45:49

问题


I have a scenario like this:

CREATE TABLE `Users` (
  `IdUser` bigint(20) NOT NULL PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `MainTable` (
  `IdLite` bigint(20) NOT NULL PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `LinkedTable` (
  `IdUser` bigint(20) NOT NULL,
  `IdLite` bigint(20) NOT NULL,
PRIMARY KEY (`IdUser`, `IdLite`),
FOREIGN KEY (`IdUser`) REFERENCES `Users` (`IdUser`),
FOREIGN KEY (`IdLite`) REFERENCES `MainTable` (`IdLite`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I'm trying to change IdLite to Unsigned with a query like this:

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `MainTable` CHANGE `IdLite` 
    `IdLite` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE `LinkedTable` CHANGE `IdLite` 
    `IdLite` BIGINT(20) UNSIGNED NOT NULL;
SET FOREIGN_KEY_CHECKS=1;

but I get error:

errno: 150 - Foreign key constraint is incorrectly formed

How can I solve?


回答1:


You can't change the data type of columns used in an existing FK constraint.

You can drop the FK constraint, change the column data types and then recreate the FK constraint:

ALTER TABLE LinkedTable
  DROP FOREIGN KEY linkedtable_ibfk_2; -- or whatever the symbol is named

ALTER TABLE MainTable
  MODIFY IdLite SERIAL; -- alias of BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE

ALTER TABLE LinkedTable
  MODIFY IdLite BIGINT UNSIGNED NOT NULL,
  ADD FOREIGN KEY (IdLite) REFERENCES MainTable (IdLite);


来源:https://stackoverflow.com/questions/37001514/change-primary-key-from-bigint-to-unsigned-bigint-when-linked-as-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!