是否可以选择和更新未知值?

时间:2019-10-29 17:26:59

标签: mysql sql

我有下表

ID      Person     Supervisor
1       Michele    2
2       James      4
3       Jacob      4
4       Francis    1

让我们说Michele(1)离开了,我希望她的Supervisor(2)接管对Michele所负责的人的监督(Francis,4)

SELECT id FROM TABLE WHERE supervisor = '1';

会给我2(米歇尔)

要更新,我只会做

UPDATE TABLE
SET Supervisor = '2' <-- can this not be hard-coded but "selected" in an UPDATE statement?
WHERE Supervisor = '1';

2 个答案:

答案 0 :(得分:0)

使用自联接。

UPDATE TABLE AS t1
JOIN TABLE AS t2 ON t1.supervisor = t2.id
SET t1.supervisor = t2.supervisor
WHERE t2.id = 1

DEMO

答案 1 :(得分:0)

您可以在子查询上使用内部联接

UPDATE TABLE t1 
INNER JOIN  (
   SELECT Supervisor FROM TABLE WHERE ID = '1' 
) T2 ON t2.Supervisor =  = t1.Supervisor

SET t1.Supervisor = t2.supervisor