Error 1452 MySQL

2020-04-16 04:22发布

问题:

Inserting data into an empty table, but got error 1452. I am not sure why MySQL mentions the NameInfo table within the error.

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)
); 

Inserted data to parent table, Departments, before child table, Employee.

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'))

Please let me know if I can provide additional information.

回答1:

Error 1452 indicates an insertion failed because a foreign key constraint couldn't be honoured.

Your query is inserting data into the Employee table, which has a foreign key constraint referring to the Departments table. If you haven't got a Department entry set up that the Employeee row refers to the insertion will fail.

You need to insert the Departments entries first, or your Employee insertions will fail this test.