我有這樣一個表: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(設置),然後處理了一批,唯一的例外似乎是在第一條語句出現。)
您需要子查詢的別名。這個想法使用名字也很糟糕。什麼,只能有一個人叫瑪麗史密斯? – Drew
@Drew當子查詢用作表達式時,不需要別名。 – Barmar
但是,您需要使用連接模式更新:http://i.imgur.com/sJDKtbZ.jpg – Drew