2016-10-10 28 views
0

我有這樣一個表:MySQL:如何從同一個表中更新外鍵?

CREATE TABLE persons (
    personID int, 
    name varchar(255), 
    mother int, 
    father int, 
PRIMARY KEY (personID), 
FOREIGN KEY (mother) REFERENCES persons(personID), 
FOREIGN KEY (father) REFERENCES persons(personID)); 

我已經插入了一些條目只有名稱和ID,現在想運行的更新,每個人與父母聯繫,假設所有三個都已經在桌子裏。

我的第一個猜測是當然這的:

UPDATE persons 
SET mother = (select personID from persons where name = 'mothersname'), 
    father = (select personID from persons where name = 'fathersname') 
WHERE name = 'personsname'; 

然而,這導致You can't specify target table 'persons' for update in FROM clause。所以我試過這個:

SET @mother = (select personID from persons where name = 'mothersname'); 
SET @father = (select personID from persons where name = 'fathersname'); 
UPDATE persons 
SET mother = @mother, 
    father = @father 
WHERE name = 'personsname'; 

這導致You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @father := (select personID from persons where name = 'fathersname');update pe' at line 1

像往常一樣使用MySQL,這個錯誤消息不是很有幫助。任何人都可以給我提示什麼是正確的語法?

(請注意,我運行更新爲JDBC的PreparedStatement,所有這三個名都通過了setString(設置),然後處理了一批,唯一的例外似乎是在第一條語句出現。)

+0

您需要子查詢的別名。這個想法使用名字也很糟糕。什麼,只能有一個人叫瑪麗史密斯? – Drew

+0

@Drew當子查詢用作表達式時,不需要別名。 – Barmar

+0

但是,您需要使用連接模式更新:http://i.imgur.com/sJDKtbZ.jpg – Drew

回答

1

使用a JOIN:

UPDATE persons AS pchild 
LEFT JOIN persons as pmom ON pmom.name = 'mothersname' 
LEFT JOIN persons AS pdad ON pdad.name = 'fathersname' 
SET pchild.mother = pmom.personID, 
    pchild.father = pdad.personID 

請注意,您必須爲每個外鍵引用單獨加入。

你的第二次嘗試,使用變量,應該工作。但是你必須在單獨的調用中執行每個查詢。大多數MySQL API不允許你在同一個調用中放置多個查詢。

+0

這看起來很有希望,但現在我在'字段列表'中獲得'未知列'pchild.mother'。 – mgtheater

+0

好吧,現在就開始工作,顯然我錯過了一個空間或其他東西。謝謝你的幫助! – mgtheater