2017-03-16 86 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

相關問題