MySQL - 根据子查询更新值

时间:2014-11-26 16:31:15

标签: mysql select sql-update

让我说我选择了,从table1返回我:

ID  Name
 1  Bob
 2  Alice
 3  Joe

然后我希望根据此结果在另一个表中使用UPDATE值:

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

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

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

我不知道如何指定WHERE-condition。

3 个答案:

答案 0 :(得分:57)

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

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

RESULTS WITH JOIN

如果您选择使用选择,则可以这样做。

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

RESULTS FROM SELECT

答案 1 :(得分:13)

 UPDATE table2
 SET name = (SELECT table1.Name FROM table1 WHERE table1.id = table2.id)
 WHERE apply_condition

编辑:#1

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

请阅读此linkanother

答案 2 :(得分:-2)

试试这个

Update table2
Set Name = (Select Name From table1 where table1.ID = table2.ID)
Where table2.ID In (Select ID From table1)