无法在mysql innodb表中创建外键

时间:2015-02-20 21:52:04

标签: mysql foreign-keys

我有以下3个表格 当我想创建这个外键时:

 alter table `template_parts_data` add constraint template_parts_data_template_row_id_foreign foreign key (`template_row_id`) references `template_rows` (`id`)

我得到他的错误: General error: 1005 Can't create table email_template.#sql-1234_1a0 (errno: 150 "Foreign key constraint is incorrectly formed")

CREATE TABLE `templates` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `templates_rows` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `template_id` int(10) unsigned NOT NULL,
 `template_part_id` int(10) unsigned NOT NULL,
 PRIMARY KEY (`id`),
 KEY `templates_rows_template_id_foreign` (`template_id`),
 KEY `templates_rows_template_part_id_foreign` (`template_part_id`),
 CONSTRAINT `templates_rows_template_id_foreign` FOREIGN KEY (`template_id`) REFERENCES `templates` (`id`),
 CONSTRAINT `templates_rows_template_part_id_foreign` FOREIGN KEY (`template_part_id`) REFERENCES `template_parts` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `template_parts` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 `html` longtext NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `template_parts_data` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `data_key` varchar(255) NOT NULL,
 `data_val` longtext NOT NULL,
 `template_row_id` int(10) unsigned NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 个答案:

答案 0 :(得分:0)

在开始创建表'template_parts_data'的行中,为什么在创建之前有表的名称。我不熟悉您正在使用的语法,但这似乎是错误的并且会导致不可预测的错误代码。