外键失败

时间:2012-03-20 15:53:35

标签: mysql foreign-keys mysql-error-1452

好的,所以我一直想弄清楚为什么我会一直收到这个特定的错误。 MySql一直给我错误代码1452.无法添加或更新子行。我的表就是这样。

CREATE  TABLE IF NOT EXISTS `ecommerce`.`departments` (
 `id` INT NOT NULL AUTO_INCREMENT ,
 `name` VARCHAR(100) NOT NULL ,
 PRIMARY KEY (`id`) )
ENGINE = MyISAM;

INSERT INTO `ecommerce`.`departments`
VALUES (1, 'Development'), (2, 'Marketing'),
       (3, 'Sales'), (4, 'Customer Service');

CREATE  TABLE IF NOT EXISTS `ecommerce`.`department_roles` (
 `id` INT NOT NULL AUTO_INCREMENT ,
 `name` VARCHAR(100) NOT NULL ,
 `map` VARCHAR(255) NOT NULL ,
 `parent_id` INT NOT NULL ,
 PRIMARY KEY (`id`) )
ENGINE = MyISAM;

INSERT INTO `ecommerce`.`department_roles`
VALUES (1, 'Admin', '/admin', 0), (2, 'Create', '/admin', 1),
       (3, 'Update', '/admin', 1), (4, 'Delete', '/admin', 1);

CREATE  TABLE IF NOT EXISTS `ecommerce`.`department_roles_map` (
 `id` INT NOT NULL AUTO_INCREMENT ,
 `department_roles_id` INT NOT NULL ,
 `departments_id` INT NOT NULL ,
 PRIMARY KEY (`id`) ,
 INDEX `fk_drm_departments` (`departments_id` ASC) ,
 INDEX `fk_drm_department_roles` (`department_roles_id` ASC) ,
 CONSTRAINT `fk_drm_departments`
  FOREIGN KEY (`departments_id` )
  REFERENCES `ecommerce`.`departments` (`id` )
  ON DELETE CASCADE
  ON UPDATE NO ACTION,
 CONSTRAINT `fk_drm_department_roles`
  FOREIGN KEY (`department_roles_id` )
  REFERENCES `ecommerce`.`department_roles` (`id` )
  ON DELETE CASCADE
  ON UPDATE NO ACTION)
ENGINE = InnoDB;

现在,当我尝试从departments和department_roles中进行选择时,我会显示数据。

SELECT * FROM department_roles;
+----+--------+--------+-----------+
| id | name   | map    | parent_id |
+----+--------+--------+-----------+
|  1 | Admin  | /admin |         0 |
|  2 | Create | /admin |         1 |
|  3 | Update | /admin |         1 |
|  4 | Delete | /admin |         1 |
+----+--------+--------+-----------+
4 rows in set (0.00 sec)

SELECT * FROM departments;
+----+--------+--------+-----------+
| id | name   | map    | parent_id |
+----+--------+--------+-----------+
|  1 | Admin  | /admin |         0 |
|  2 | Create | /admin |         1 |
|  3 | Update | /admin |         1 |
|  4 | Delete | /admin |         1 |
+----+--------+--------+-----------+
4 rows in set (0.00 sec)

但是,当我尝试插入department_roles_map时,我明白了。

INSERT INTO department_roles_map(department_roles_id, departments_id) VALUES (1, 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ecommerce`.`department_roles_map`, CONSTRAINT `fk_drm_departments` FOREIGN KEY (`departments_id`) REFERENCES `departments` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION)

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

首先,我对你设法创建一个对两个MyISAM表有FK引用的InnoDB表感到印象深刻!

尝试使用InnoDB引擎创建所有三个表并再次尝试....

答案 1 :(得分:0)

父表和子表都需要使用InnoDB存储引擎,但您使用MyISAM作为父表。

我的猜测是已经存在一个名为department_roles_map的表,所以当你运行CREATE TABLE IF NOT EXISTS时它会失败,因为该表已经存在,并忽略了错误。然后,当您尝试将数据插入其他 department_roles_map时,它会因FK错误而失败。

但这只是猜测。

我同意Tom Mac,尝试使用InnoDB创建所有3个表,但是您还应该确认没有其他具有这些名称的表已经存在。