I have created tables in MySQL Workbench as shown below :
ORDRE table:
CREATE TABLE Ordre (
OrdreID INT NOT NULL,
OrdreDato DATE DEFAULT NULL,
KundeID INT DEFAULT NULL,
CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
ENGINE = InnoDB;
PRODUKT table:
CREATE TABLE Produkt (
ProduktID INT NOT NULL,
ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
ProduktFarge VARCHAR(20) DEFAULT NULL,
Enhetpris INT DEFAULT NULL,
CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
ENGINE = InnoDB;
and ORDRELINJE table:
CREATE TABLE Ordrelinje (
Ordre INT NOT NULL,
Produkt INT NOT NULL,
AntallBestilt INT DEFAULT NULL,
CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
ENGINE = InnoDB;
so when I try to insert values into ORDRELINJE
table i get:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (
srdjank
.Ordrelinje
, CONSTRAINTOrdrelinje_fk
FOREIGN KEY (Ordre
) REFERENCESOrdre
(OrdreID
))
I've seen the other posts on this topic, but no luck. Am I overseeing something or any idea what to do?
While inserting the foreign key attribute values, first verify the attributes type, as well as primary key attribute value in the parent relation, if the values in parent relation matches, then you can easily insert/update child attribute values.
Your
ORDRELINJE
table is linked withORDER
table using a foreign key constraintconstraint Ordrelinje_fk foreign key(Ordre) references Ordre(OrdreID)
according to whichOrdre int NOT NULL,
column of tableORDRELINJE
must match anyOrdre int NOT NULL,
column ofORDER
table.Now what is happening here is, when you are inserting new row into
ORDRELINJE
table, according to fk constraintOrdrelinje_fk
it is checkingORDER
table if theOrdreID
is present or not and as it is not matching with any OrderId, Compiler is complaining for foreign key violation. This is the reason you are getting this error.Foreign key is the primary key of the other table which you use in any table to link between both. This key is bound by the foreign key constraint which you specify while creating the table. Any operation on the data must not violate this constraint. Violation of this constraint may result in errors like this.
Hope I made it clear.