2012-02-28 25 views
1

我有一個包含複合主鍵「名稱」和「ID」的表。這些字段實際上是「名稱」,「ID」,「電話」,「金額」,「單位」,「別名」。我有查詢重複鍵更新失敗,錯誤爲「無法添加或更新子行」

insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable 
on duplicate key update phone=values(phone),amount=values(amount). 

MySQL的吐出以下錯誤:

Cannot add or update a child row: a foreign key constraint fails. 

順便說一句, 「ID」 是一個外鍵。

任何幫助?

如下要求,對於其他表的模式是

CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT, 
`DOBId` int(11) NOT NULL, 
`bankAccount` int(11) DEFAULT NULL, 
`partialAmount` int(11) NOT NULL DEFAULT '0', 
`id` int(11) NOT NULL, 
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
`notes` varchar(299) DEFAULT NULL, 
`latitude` decimal(8,5) DEFAULT NULL, 
`longitude` decimal(8,5) DEFAULT NULL, 
    PRIMARY KEY (`otherId `), 
    KEY `DOBId ` (`DOBId `), 
    KEY `bankAccount ` (`bankAccount `), 
    KEY `id ` (`id `) 
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8; 

爲myTable的

CREATE TABLE `myTable` (
    `name` int(11) NOT NULL, 
    `id` int(11) NOT NULL, 
    `appleNumber` int(11) DEFAULT NULL, 
    `amount` int(11) DEFAULT NULL, 
    `windowsNumber` int(11) DEFAULT NULL, 
    `phone` int(11) DEFAULT NULL, 
    `pens` int(11) DEFAULT NULL, 
    `pencils` int(11) DEFAULT NULL, 
    PRIMARY KEY (`name`,`id`), 
    KEY `id` (`id`), 
    CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`) 
+0

你可以發佈'MyTable'的模式嗎? – 2012-02-28 22:25:43

+0

我在上面發佈架構 – tribal 2012-02-28 23:01:13

+0

爲什麼myTable.name是一個int(11)? – 2012-02-28 23:01:38

回答

3

問題似乎是您在myTable上的FK約束引用yet_another的ID,因此當您插入來自anotherTable的ID時,您將破壞此FK約束。機會有anotherTable中的ID不存在於yet_another表中。

瞭解這是在黑暗中拍攝的,基於您發佈的抽象模式。如果你想要一個更加可靠的答案,我必須看到實際的模式。

+0

你明白了!另一個表中的某些ID不存在於另一個 – tribal 2012-02-29 01:05:55

+0

感謝大家幫忙 – tribal 2012-02-29 01:07:27

+0

啊哈很酷。希望這是一個簡單的修復,祝你好運。 – 2012-02-29 01:07:50

0

的上重複鍵適用於主鍵。我認爲你使用的是innodb。這在外鍵約束上失敗。你表MyTable的哪些值是外鍵?請發佈顯示所有鍵和約束的表的create語句以獲得更詳細的幫助。

只是一個猜測,但對於笑話我敢打賭,這是一個不在插入的列,它是一個不允許空值的外鍵。

+0

我在上面顯示模式 – tribal 2012-02-28 23:00:48

相關問題