文章内容

2018/2/8 15:33:52,作 者: 黄兵

There is no index in the referenced table where the referenced columns appear as the first columns

最近在使用alembic更新数据库的时候,提示如下错误:

sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1215, 'Cannot add foreign key constraint')

[SQL: 'ALTER TABLE users ADD FOREIGN KEY(city) REFERENCES `CH_REGION` (`ID`)']

错误提示是无法建立外键,我直接用后面的SQL语句来查询数据库。

ALTER TABLE users ADD FOREIGN KEY(city) REFERENCES `CH_REGION` (`ID`)

之后提示错误如下:

Create table 'Mxxxxl_Development/#sql-39a_c03' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.

出现这个错误主要是:因为引用的主键与外键数据类型不一样,一个是int(11)数据类型,一个是bigint(10)数据类型。

引用官方文档:

外键和引用键中的相应列必须具有相似的数据类型。整数类型的大小和符号必须相同。字符串类型的长度不需要相同。对于非二进制(字符)字符串列,字符集和归类必须相同。

解决方案:

将int(11)改为bigint(10)数据类型,之后再次执行SQL查询。没有报错,问题解决。

参考资料:

MySQL Creating tables with Foreign Keys giving errno: 150

MySQL cannot create foreign key constraint


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - There is no index in the referenced table where the referenced columns appear as the first columns

分享到:

发表评论

评论列表