这个错误是mysql中非常常见的外键约束创建失败错误。
错误本质
错误信息:
1005 - can't create table 'zkac.#sql-1350_1' (errno: 150)
这表示mysql在尝试创建表或添加外键约束时失败了,具体是外键约束创建过程中遇到了问题。
根本原因排查清单
1. 数据类型不匹配(最常见原因)
检查方法:
show create table navigation_target_point_info; show create table task_type_info;
- 必须满足:
ntpi_task_type_name和robot_task_type_name的数据类型完全一致- 对于字符串类型,长度、字符集和排序规则也必须一致
2. 被引用列不是主键或唯一键
检查方法:
show index from task_type_info where key_name = 'primary' or column_name = 'robot_task_type_name';
解决方案:
-- 如果不是主键或唯一键,需要添加 alter table task_type_info add unique index idx_robot_task_type_name (robot_task_type_name);
3. 存储引擎不支持外键
检查方法:
show table status like 'navigation_target_point_info'; show table status like 'task_type_info';
解决方案:
-- 转换为innodb引擎 alter table navigation_target_point_info engine=innodb; alter table task_type_info engine=innodb;
4. 数据不一致问题
检查方法:
-- 查找外键表中有但主键表中没有的值 select distinct ntpi.ntpi_task_type_name from navigation_target_point_info ntpi left join task_type_info tti on ntpi.ntpi_task_type_name = tti.robot_task_type_name where ntpi.ntpi_task_type_name is not null and tti.robot_task_type_name is null;
- 解决方案:
- 删除无效数据
- 或在主表中添加缺失的记录
5. 表不存在或列名错误
检查方法:
-- 确认表和列是否存在
select * from information_schema.columns
where table_schema = 'zkac'
and table_name in ('navigation_target_point_info', 'task_type_info')
and column_name in ('ntpi_task_type_name', 'robot_task_type_name');以上就是mysql错误1005(errno: 150)的原因分析与解决方案的详细内容,更多关于mysql错误1005(errno: 150)的资料请关注代码网其它相关文章!
发表评论