2017-03-16 89 views
0

我对SQL仍然比较陌生。我正在更新数据库,并且遇到了此消息。问题是,我已经执行了此插入,但不得不删除它,因为我三次输入相同的地址,而不是一次。MySQL工作台:错误代码1452.无法添加或更新子行:外键约束失败

任何人可以帮助我,我不明白什么是错的:

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

我不断收到此消息:

> 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 
+0

当它没有找到出现这种错误在主键表中提供了外键。您的表'liegenschaft'中的插入查询中的一个嵌套选择查询必须为null或不匹配。 – ARr0w

回答

0

对于要插入的liegenschaft.adressid,您没有条目adresse.AID中的条目。

您在外键中指定了错误的列,插入或者您忘记将数据插入到该列中。

你需要做其中的一个:

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

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

或更改外键在ortID点,而不是AID

+0

非常感谢。我使用了错误的外键。我不记得改变它。谢谢您的帮助! :) – Earthnuts

0

在liegenschaft列adressid应有的关键adressID和没有oid。

尝试(假设存在为每个地址仅一个条目)

插入到liegenschaft (liegenschafttypid,adressid)值 ((从liegenschaft_typ选择ltypid其中name = '故居/丰资本'),(选择adressID来自ort where name ='Langenthal'且plz ='4900'))

+0

非常感谢您的声明,我不得不做出一些小改动(忘记补充说明信息,对不起),但非常感谢帮助,我一直在这里坐了30分钟! – Earthnuts

相关问题