I'm crazy trying to solve an error, but i can't. With mysql. Foreign key error while doing INSERT INTO.

StackOverflow https://stackoverflow.com/questions/16780516

Вопрос

In mysql, when i try to do:

INSERT INTO Comandes_Productes(Id_Comanda, Id_Producte) VALUES ('60', '10009') --> (or others values)

for example, i get this error message: #1452 - Cannot add or update a child row: a foreign key constraint fails (cafeteria.comandes_productes, CONSTRAINT comandes_productes_ibfk_2 FOREIGN KEY (Id_Producte) REFERENCES comandes (Id_Comanda) ON UPDATE CASCADE)

I try to do a lot of solutions that are proposed the next link, but, too i didn't solve the error.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I will get you the code, to see if i have an error in it.

CREATE TABLES:

CREATE TABLE Comandes (  
    Id_Comanda INTEGER(9) AUTO_INCREMENT,  
    Quantitat INTEGER(4),  
    Id_Proveidor INTEGER(9) NOT NULL,  
    Data DATE,  
PRIMARY KEY (Id_Comanda),  
FOREIGN KEY (Id_Proveidor) REFERENCES Proveidors(Id_Proveidor) ON UPDATE CASCADE    
) CHARACTER SET utf8 COLLATE utf8_spanish_ci;  

CREATE TABLE Productes (  
    Id_Producte INTEGER(9) AUTO_INCREMENT,  
    Marca VARCHAR(15),  
    Nom_Producte VARCHAR(30),  
    Preu_Producte FLOAT(4,2),  
    Quantitat INTEGER(4),  
    Descripcio VARCHAR(50),  
Id_Proveidor INTEGER(9),  
PRIMARY KEY (Id_Producte)  
) AUTO_INCREMENT=10001 CHARACTER SET utf8 COLLATE utf8_spanish_ci;  


CREATE TABLE Comandes_Productes (  
        Id_Comanda INTEGER(9),  
        Id_Producte INTEGER(9),  
        PRIMARY KEY (Id_Producte, Id_Comanda),  
FOREIGN KEY (Id_Producte) REFERENCES Productes (Id_Producte) ON UPDATE CASCADE,  
FOREIGN KEY (Id_Producte) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE    
) CHARACTER SET utf8 COLLATE utf8_spanish_ci;  

And yes, i already have the foreing keys values in the tables "Comandes" and "Productes". All tables are with InnoDB, too i try to delete all database and create other time, but.. nothing... I see the specifications of the tables and too are all the same.

In what i fails? Please help me! I can't continue with my project...

Это было полезно?

Решение

I see one problem with your Comandes_Productes table:

FOREIGN KEY (Id_Producte) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE

probably it should be

FOREIGN KEY (Id_Comanda) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE

Also, I am not much into MySQL, but probably you shoud not use single quotes when entering numerical values.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top