好的,所以我一直在試圖弄清楚爲什麼我一直在收到這個特定的錯誤。 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;
現在,當我嘗試從部門和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)
任何幫助將不勝感激!
工作正常!謝謝! – 2012-03-20 16:10:46