我有这样的场景:
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;
我尝试使用以下查询将IdLite
更改为Unsigned
:
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;
但我收到错误:
错误:150 - 外键约束形成错误
我该如何解决?
答案 0 :(得分:3)
您无法更改现有FK约束中使用的列的数据类型。
您可以删除FK约束,更改列数据类型,然后重新创建FK约束:
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);