MySQL:如何从同一个表更新外键?

时间:2016-10-10 17:32:26

标签: mysql foreign-keys

我有一张这样的表:

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()进行设置,然后批量处理。异常似乎发生在第一个语句中。)

1 个答案:

答案 0 :(得分:1)

使用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都不允许您在同一个调用中放置多个查询。