无法添加或更新子行:外键约束失败

时间:2013-11-27 09:48:01

标签: php mysql sql database phpmyadmin

这是我面临的问题的两个表的create语句: 第一张表:

 CREATE TABLE `hrm__companyteam` (
 `id_team` int(11) NOT NULL AUTO_INCREMENT,
 `id_department` int(11) NOT NULL,
 `team_name` varchar(255) NOT NULL DEFAULT '',
 `notes` mediumtext NOT NULL,
 PRIMARY KEY (`id_team`),
 KEY `id_company` (`id_department`),
 CONSTRAINT `hrm__companyTeam_ibfk_1` FOREIGN KEY (`id_department`) REFERENCES `hrm__companydepartment` (`id_department`) ON DELETE CASCADE,
 CONSTRAINT `hrm__companyteam_ibfk_1` FOREIGN KEY (`id_department`) REFERENCES `hrm__companydepartment` (`id_department`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

第二张表

CREATE TABLE `hrm__companyjobtitle` (
 `id_job_title` int(11) NOT NULL AUTO_INCREMENT,
 `id_team` int(11) NOT NULL DEFAULT '0',
 `job_title_name` varchar(255) NOT NULL DEFAULT '',
 `notes` mediumtext NOT NULL,
 PRIMARY KEY (`id_job_title`),
 KEY `id_division` (`id_team`),
 CONSTRAINT `hrm__companyJobTitle_ibfk_1` FOREIGN KEY (`id_team`) REFERENCES `hrm__companyteam` (`id_team`) ON DELETE CASCADE,
 CONSTRAINT `hrm__companyjobtitle_ibfk_1` FOREIGN KEY (`id_team`) REFERENCES `hrm__companyteam` (`id_team`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

当我尝试执行以下查询时:

INSERT INTO `hr_db`.`hrm__companyjobtitle` (

`id_job_title` ,
`id_team` ,
`job_title_name` ,
`notes`
)
VALUES (
'1',  '1',  'IT',  ''
)

我收到此错误:

1452 - 无法添加或更新子行:外键约束失败(hr_dbhrm__companyjobtitle,CONSTRAINT hrm__companyJobTitle_ibfk_1 FOREIGN KEY(id_team)REFERENCES {{1 }(hrm__companyteam)ON DELETE CASCADE)

请帮忙......我做错了什么。如果您需要任何进一步的细节,请告诉我。

1 个答案:

答案 0 :(得分:1)

我使用了这些陈述:

CREATE TABLE `hrm__companyteam` (
    `id_team` INT(11) NOT NULL AUTO_INCREMENT,
    `id_department` INT(11) NOT NULL,
    `team_name` VARCHAR(255) NOT NULL DEFAULT '',
    `notes` MEDIUMTEXT NOT NULL,
    PRIMARY KEY (`id_team`),
    INDEX `id_company` (`id_department`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4;


CREATE TABLE `hrm__companyjobtitle` (
    `id_job_title` INT(11) NOT NULL AUTO_INCREMENT,
    `id_team` INT(11) NOT NULL DEFAULT '0',
    `job_title_name` VARCHAR(255) NOT NULL DEFAULT '',
    `notes` MEDIUMTEXT NOT NULL,
    PRIMARY KEY (`id_job_title`),
    INDEX `id_division` (`id_team`),
    CONSTRAINT `hrm__companyJobTitle_ibfk_1` FOREIGN KEY (`id_team`) REFERENCES `hrm__companyteam` (`id_team`) ON DELETE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4;


INSERT INTO hrm__companyteam (id_team, id_department, team_name, notes) VALUES (1, 1, 'Sales', ''), (2, 2, 'Team no 1', '');

INSERT INTO hrm__companyjobtitle (id_job_title , id_team , job_title_name , notes ) VALUES ( '1', '1', 'IT', '' );

并且所有这些都成功运行而没有任何错误