我正在努力使用以下查询创建外键:
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
) referencesstructures
(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/