错误1452 MySQL

时间:2013-11-17 07:10:39

标签: mysql foreign-keys

将数据插入空表,但得到错误1452.我不确定为什么MySQL会在错误中提到NameInfo表。

CREATE TABLE NameInfo (
Language VARCHAR(7) NOT NULL,
Status VARCHAR(13) NOT NULL, 
Standard VARCHAR(13) NOT NULL, 
Name VARCHAR(13) NOT NULL, 
Name_ID INT(4) NOT NULL, 
Place_ID INT(9) NOT NULL, 
Supplier_ID INT(4) NOT NULL, 
Date_Supplied DATE NOT NULL, 
PRIMARY KEY (Name_ID),
FOREIGN KEY (Supplier_ID) REFERENCES Supplier(Supplier_ID),
FOREIGN KEY (Place_ID) REFERENCES Place(Place_ID) 
);


CREATE TABLE Departments ( 
Dept_ID INT(6) NOT NULL,
Dept_NAME VARCHAR(25) NOT NULL, 
DeptHead_ID INT(6) NOT NULL,
DeptAA VARCHAR(20) NOT NULL, 
ParentDept_ID INT(4) NOT NULL,
Location VARCHAR(10) NOT NULL, 
DeptType VARCHAR(12) NOT NULL, 
Primary key (Dept_ID)
); 

CREATE TABLE Employee ( 
Emp_ID INT(6) NOT NULL, 
Name VARCHAR(15) NOT NULL,
Dept_ID INT(6) NOT NULL, 
Tax_ID INT(4) NOT NULL, 
Country VARCAR(15) NOT NULL, 
Hire_Date DATE NOT NULL,
Birth_Date DATE NOT NULL, 
Salary INT(6) NOT NULL, 
Bonus INT(6) NOT NULL,
AddressInfo VARCHAR(30) NOT NULL,
PRIMARY KEY(Emp_ID),
FOREIGN KEY(Dept_ID) REFERENCES Departments(Dept_ID)
); 

在子表,员工之前将数据插入父表Departments。

INSERT INTO Departments
VALUES (040124,'Human Resource Division',405802,'Mohammed Siddiqui',1001,'California','HR');

INSERT INTO Employee
VALUES (901126,'Kenneth Tran',040126,3013,'United States',06/01/2013,06/01/1992,80430,500,'N. 2nd St. Santa Clara, CA.');

ERROR 1452 (23000): Cannot add or update a child: a foreign key constraint fails     ('namesinc'_'employee', CONSTRAINT 'employee-ibfk_1 'FOREIGN KEY ('Dept_ID') REFERENCES 'DEPARTMENTS' ('DEPT_ID'))

如果我能提供更多信息,请告诉我。

1 个答案:

答案 0 :(得分:5)

错误1452表示插入失败,因为无法遵守外键约束。

您的查询是将数据插入Employee表,该表具有引用Departments表的外键约束。如果您没有设置Department条目,Employeee行引用,则插入将失败。

您需要先插入Departments条目,否则Employee插入将无法通过此测试。