2012-03-20 91 views
2

好的,所以我一直在試圖弄清楚爲什麼我一直在收到這個特定的錯誤。 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) 

任何幫助將不勝感激!

回答

1

首先,我印象深刻的是,您設法創建了一個InnoDB表,該表的FK引用了兩個MyISAM表!

嘗試創建三個表InnoDB引擎,並再次嘗試....

+0

工作正常!謝謝! – 2012-03-20 16:10:46

0

無論是家長和孩子的表需要使用InnoDB存儲引擎,但你使用的MyISAM父表。

我的猜測是已經有一個名爲department_roles_map的表,所以當你運行CREATE TABLE IF NOT EXISTS時,它失敗了,因爲表已經存在,並且忽略了錯誤。然後,當您嘗試將數據插入其他 department_roles_map時,它會因FK錯誤而失敗。

但這只是一個猜測。

我同意Tom Mac,嘗試使用InnoDB創建所有3個表,但是您還應該確認沒有其他具有這些名稱的表已經存在。