Mysql转储还原失败:无法添加外键约束

Sak*_*pta 7 mysql mysqldump

我正在尝试恢复使用mysqldump创建的转储.恢复原状,我明白了

第63行的错误1215(HY000):无法添加外键约束

DROP TABLE IF EXISTS `channel_tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `channel_tags` (
  `channel_tag_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `channel_id` bigint(20) NOT NULL,
  `tag_name` varchar(60) NOT NULL,
  PRIMARY KEY (`channel_tag_id`),
  KEY `channel_id_idx` (`channel_id`),
  KEY `tag_name_idx` (`tag_name`),
  CONSTRAINT `ct_channel_fk` FOREIGN KEY (`channel_id`) REFERENCES `channel_shard` (`channel_id`),
  CONSTRAINT `ct_tag_fk` FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB AUTO_INCREMENT=833 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tags` (
  `tag_name` varchar(60) NOT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`tag_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
Run Code Online (Sandbox Code Playgroud)

create table语句的顺序是相同的.

SHOW ENGINE INNODB状态\ G给了我这个:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2015-12-07 17:20:16 1ac30b000 Error in foreign key constraint of table sde/channel_tags:
 FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4:
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.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Run Code Online (Sandbox Code Playgroud)

有人能让我知道这里发生了什么吗?

小智 5

我也收到了这个错误。

我猜你和我做了同样的事情:将整个数据库设置为UTF8并将一些列/表更改为UTF8MB4之后。

我不知道如何解决它。但是,有一个解决方法:UTF8MB4在转储 SQL 文件中将所有内容改回 UTF8,将其恢复到数据库中,并UTF8MB4通过以下命令手动更改特定列:

ALTER DATABASE [dbname] CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

ALTER TABLE [tablename] CHANGE [colname] [colname] VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE [tablename] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS=1;
Run Code Online (Sandbox Code Playgroud)


小智 5

我的转储和数据库中没有 utf8mb4 字符集,但遇到了问题。

我解决了它删除所有表并在之后恢复我的转储。

使用以下内容:如何在没有 DROP 数据库权限的情况下从命令行删除所有 MySQL 表?