我有这样一个表: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