MySQL - 基于子查询更新值

2022-01-17 00:00:00 sql-update select mysql

假设我有选择,它从 table1 中返回:

let's say I have select, which return me from table1:

ID  Name
 1  Bob
 2  Alice
 3  Joe

然后我想根据这个结果在另一个表中更新值:

Then I want UPDATE values in another table based on this result:

UPDATE table2 SET Name = table1.Name WHERE ID = table1.ID

据我了解,我只能在一个地方进行内部选择,例如:

As I understood, I can only do internal select in one place, like:

UPDATE table2 SET Name = (select Name from table1) WHERE ...

而且我不知道如何指定 WHERE 条件.

And I don't know how to specify WHERE-condition.

推荐答案

你应该做的就是像这样加入表格.

all you should do is just join the tables like this.

UPDATE table2 t2
JOIN table1 t1 ON t1.id = t2.id
SET t2.name = t1.name;

加入的结果

如果你打算用一个选择来做,你可以这样做.

if you are set on doing it with a select you could do it like this.

UPDATE table2 t2,
(   SELECT Name, id 
    FROM table1 
) t1
SET t2.name = t1.name
WHERE t1.id = t2.id

选择结果

相关文章