此sql来自mysqldump文件,它一直给我:Error Code: 1215. Cannot add foreign key constraint
由于这种不一致,我已经为整个下午苦苦挣扎,但仍然不知道问题出在哪里。

DROP TABLE IF EXISTS `regions`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `regions` (
  `region_id` bigint(20) unsigned AUTO_INCREMENT,
  `region_code` int(6) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `parent_code` int(6) unsigned DEFAULT NULL,
  `type` varchar(255) NOT NULL,
  PRIMARY KEY (`region_id`),
  UNIQUE KEY `ui_RegionCode` (`region_code`),
  CONSTRAINT `regions_ParentCode_RegionCode` FOREIGN KEY (`parent_code`) REFERENCES `regions` (`region_code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3525 DEFAULT CHARSET=utf8;

最佳答案

看起来像“ CONSTRAINT regions_ParentCode_RegionCode外键(parent_code)参考regions”,是对表区域的自引用。

尝试不使用此语句创建表

CREATE TABLE `regions`(
  `region_id` BIGINT(20) UNSIGNED AUTO_INCREMENT,
  `region_code` INT(6) UNSIGNED NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  `parent_code` INT(6) UNSIGNED DEFAULT NULL,
  `type` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`region_id`),
  UNIQUE KEY `ui_RegionCode` (`region_code`)
) ENGINE = INNODB AUTO_INCREMENT = 3525 DEFAULT CHARSET = utf8;


并在此之后添加

ALTER TABLE regions
        ADD
        CONSTRAINT `regions_ParentCode_RegionCode`
        FOREIGN KEY (`parent_code`) REFERENCES `regions` (`region_code`)
        ON DELETE CASCADE
        ON UPDATE CASCADE;

关于mysql - 原始mysqldump文件导入:无法添加外键约束?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28761451/

10-12 03:18