本文介绍了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
选择结果
这篇关于MySQL - 基于子查询更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!