2016-10-10 70 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