简体   繁体   中英

MySQL Workbench: Error Code 1452. Cannot add or update a child row: a foreign key constraint fails

I'm still fairly new to SQL. I'm updating a DB and I came across this message. The problem is, I've already executed this insert before but had to delete it due to me entering the same address 3 times instead of once.

Can anybody help me, I don't understand what is wrong:

> insert into ort  
    (plz, name) values    
    ('4900', 'Langenthal')  
;

>insert into adresse  
    (strasse, strassennr, ortID) values  
    ('Eisenbahnstrasse', '7', (select oid from ort where name = 'Langenthal' and plz='4900'))  
;
>
insert into liegenschaft  
    (liegenschafttypid, adressid) values  
    ((select ltypid from liegenschaft_typ where name = 'Wohnhaus / Firma'), (select oid from ort where name = 'Langenthal' and plz = '4900'))  
;

I keep on getting this message:

> 0 16  14:09:25    insert into liegenschaft   (liegenschafttypid, adressid) values
     ((select ltypid from liegenschaft_typ where name = 'Wohnhaus / Firma'),   (select oid from ort where name = 'Langenthal' and plz = '4900'))    Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`parking`.`liegenschaft`, CONSTRAINT `FK_adresse` FOREIGN KEY (`adressID`) REFERENCES `adresse` (`AID`))    0.015 sec

The column adressid in liegenschaft shall have the key adressID and not oid.

Try (assume that there just one entry for each address)

insert into liegenschaft (liegenschafttypid, adressid) values ((select ltypid from liegenschaft_typ where name = 'Wohnhaus / Firma'), (select adressID from ort where name = 'Langenthal' and plz = '4900'))

You don't have entry in column adresse.AID for liegenschaft.adressid that you want to insert.

You either specified wrong column in foreign key, insert or you forgot to insert data into that column.

You need to do one of those:

insert into adresse
(strasse, strassennr, AID) values
('Eisenbahnstrasse', '7', (select oid from ort where name = 'Langenthal' and plz='4900'));

or

insert into adresse
(strasse, strassennr, ortID, AID) values
('Eisenbahnstrasse', '7', (select oid from ort where name = 'Langenthal' and plz='4900'), (select oid from ort where name = 'Langenthal' and plz='4900'));

or alter that foreign key to point at ortID instead AID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM