原始mysqldump文件导入:无法添加外键约束?

时间:2015-02-27 09:23:28

标签: mysql sql debugging datatable

这个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;

1 个答案:

答案 0 :(得分:0)

看起来像“CONSTRAINT regions_ParentCode_RegionCode FOREIGN KEY(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;