mysql - 错误 1215 : Can't add foreign key constraint (InnoDB)

标签 mysql foreign-keys innodb

我正在努力使用以下查询创建外键:

alter table `users` add constraint `users_sales_partner_id_foreign` foreign key (`sales_partner_id`) references `structures` (`sales_partner_id`) on update cascade

InnoDB 日志显示,它无法匹配此索引:

2017-02-27 10:25:47 Error in foreign key constraint of table website_backend/users: foreign key (sales_partner_id) references structures (sales_partner_id) on update cascade: Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.

我已经检查了拼写错误和数据类型不兼容性,但一切似乎都正常:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `sales_partner_id` int(11) NOT NULL,
  `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `state` enum('pending','confirmed','active','deactivated') COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_profile_id_unique` (`profile_id`),
  UNIQUE KEY `users_sales_partner_id_unique` (`sales_partner_id`),
  UNIQUE KEY `users_email_unique` (`email`),
  CONSTRAINT `users_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

CREATE TABLE `structures` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sales_partner_id` int(11) NOT NULL,
  `sales_partner_structure` int(11) DEFAULT NULL,
  `active` tinyint(1) NOT NULL,
  `blocked` tinyint(1) NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

我无法解决我的问题,有人有线索吗?提前致谢!

最佳答案

感谢 Paul Spiegel 的提醒,我只能将 FK 设置为索引字段。经过另一次审查后,我注意到我引用的字段没有被索引,这解决了我的问题。

关于mysql - 错误 1215 : Can't add foreign key constraint (InnoDB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42485401/

相关文章:

php - 计算时间并将其与 PHP 中的 mysql 时间进行比较

python - 如何在 Django 中允许空外键?

mysql - 实现关系数据库方案

mysql - 如何修复创建外部约束时的索引错误

mysql - PDO 事务提交而不是回滚

php - TinyMCE 和 MySQL PHP 输出

mysql - Apache2 Mysql 和 php7.0 function_exists ('mysql_connect' ) 返回 false

php - 什么更快? File_exist 或 MySQL 查询?

Innodb 中的 MySQL min() 行为

mySQL - 限制 JOIN 语句一侧返回的行数?