问题描述
我有以下表格结构:
此图显示了 referral_sources 表的表结构,其中 (referral_source,agency_id)
被设为唯一键。
此图片来自 lead_sources 表,此处 (source,agency_id)
是唯一键。我正在尝试将 lead_sources 表的 (referral_source,agency_id)
作为 referral_sources 的 (referral_source,agency_id)
的外键。
我尝试过以下查询:
ALTER TABLE `lead_sources` ADD CONSTRAINT `fk_referral_source` FOREIGN KEY (`referral_source`,`agency_id`) REFERENCES `referral_sources`(`referral_source`,`agency_id`) ON DELETE SET NULL ON UPDATE CASCADE;
从两个表中可以看出,两个表的列都具有相同的数据类型、数据大小和字符集。我仍然面临外键问题 There is no index in the referenced table where the referenced columns appear as the first columns
。
我已尝试将两列、数据类型、数据大小、innodb 引擎相互匹配,但仍然无法正常工作。
解决方法
当您创建 FK 约束时,您可能有来自双方的索引。
ALTER TABLE `lead_sources`
ADD CONSTRAINT `fk_referral_source`
FOREIGN KEY (`referral_source`,`agency_id`)
REFERENCES `referral_sources`(`referral_source`,`agency_id`)
ON DELETE SET NULL ON UPDATE CASCADE;
对于这个语句,你必须有一个包含所有引用的索引。列顺序相同,即 referral_sources (referral_source,agency_id)
。 (referral_source,agency_id)
是前缀的索引(例如,(referral_source,agency_id,id,created_at)
)也很有用。此索引必须在此语句执行之前存在。
从 FK 的另一边来看,索引 lead_sources (referral_source,agency_id)
也必须存在。并且,如上例所示,参考。列可以是前缀。但是如果这样的索引不存在,那么它会被自动创建。