我尝试修改之前设置的NOT NULL
字段以接受NULL
值。
当我尝试插入记录时,我收到此错误:
A foreign key constraint failed.
我的架构中有两个表,一个名为Customer
,另一个名为referralAgent
,其中定义了 一对多 关系在它们之间,使用referralAgentId
作为customer表的外键。
虽然父表的字段中没有任何NOT NULL
约束,即customer
,但我无法在外键字段中插入NULL
值。
CREATE TABLE
代码:
CREATE TABLE IF NOT EXISTS `watson_schema`.`referralagent` (
`idReferralAgent` INT(11) NOT NULL,
`firstName` VARCHAR(45) NOT NULL,
`lastName` VARCHAR(45) NOT NULL,
`test` VARCHAR(45) NULL DEFAULT NULL,
PRIMARY KEY (`idReferralAgent`))
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `watson_schema`.`customer` (
`idUser` INT(11) NOT NULL AUTO_INCREMENT,
`firstName` VARCHAR(45) NOT NULL,
`lastName` VARCHAR(45) NOT NULL,
`address` VARCHAR(80) NOT NULL,
`postCode` VARCHAR(45) NOT NULL,
`profession` VARCHAR(45) NOT NULL,
`phoneNumWork` VARCHAR(16) NOT NULL,
`phoneNumMobile` VARCHAR(16) NOT NULL,
`phoneNumHome` VARCHAR(16) NOT NULL,
`nationality` INT(11) NOT NULL,
`countryResidence` INT(11) NOT NULL,
`countryBirth` INT(11) NOT NULL,
`entityStatusIdStatus` INT(11) NOT NULL,
`ReferralAgent_idReferralAgent` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`idUser`),
INDEX `fk_Customers_nationality1_idx` (`nationality` ASC),
INDEX `fk_Customers_Country1_idx` (`countryResidence` ASC),
INDEX `fk_Customers_Country2_idx` (`countryBirth` ASC),
INDEX `fk_Customer_EntityStatus1_idx` (`entityStatusIdStatus` ASC),
INDEX `fk_Customer_ReferralAgent1_idx` (`ReferralAgent_idReferralAgent` ASC),
CONSTRAINT `fk_Customers_Country1`
FOREIGN KEY (`countryResidence`)
REFERENCES `watson_schema`.`country` (`idCountry`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Customers_Country2`
FOREIGN KEY (`countryBirth`)
REFERENCES `watson_schema`.`country` (`idCountry`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Customers_nationality1`
FOREIGN KEY (`nationality`)
REFERENCES `watson_schema`.`nationality` (`idNationality`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Customer_EntityStatus1`
FOREIGN KEY (`entityStatusIdStatus`)
REFERENCES `watson_schema`.`entitystatus` (`idStatus`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Customer_ReferralAgent1`
FOREIGN KEY (`ReferralAgent_idReferralAgent`)
REFERENCES `watson_schema`.`referralagent` (`idReferralAgent`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 21
DEFAULT CHARACTER SET = utf8;
INSERT INTO `watson_schema`.`customer`
(`idUser`,
`firstName`,
`lastName`,
`address`,
`postCode`,
`profession`,
`phoneNumWork`,
`phoneNumMobile`,
`phoneNumHome`,
`nationality`,
`countryResidence`,
`countryBirth`,
`entityStatusIdStatus`,
`ReferralAgent_idReferralAgent`)
VALUES
("22",
"Giannis",
"Komikos",
"Theofilou",
"2242",
"Coffeeman",
"22345672",
"99874568",
"22454547",
"6",
"2",
"3",
"5",
"");
答案 0 :(得分:2)
您没有插入null。您正在插入一个空字符串。将ReferralAgent_idReferralAgent从insert语句中删除或将insert语句中的最后一个值从“”更改为NULL。插入失败,因为父表中没有等于“”的键。