本文介绍了MySQL-根据子查询更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说我选择了,这使我从表1中返回:
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
这篇关于MySQL-根据子查询更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!