MySQL - 基于子查询更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27154265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - Update values based on subquery
提问by MasterClass
let's say I have select, which return me from table1:
假设我有选择,它从表 1 返回我:
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 ...
And I don't know how to specify WHERE-condition.
而且我不知道如何指定 WHERE 条件。
回答by John Ruddell
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
回答by Rajib Ghosh
回答by asantaballa
Try this
尝试这个
Update table2
Set Name = (Select Name From table1 where table1.ID = table2.ID)
Where table2.ID In (Select ID From table1)