表1:
id name desc
-----------------------
1 a abc
2 b def
3 c adf
表2:
id name desc
-----------------------
1 x 123
2 y 345
如何运行 sql update 查询,该查询可以使用相同的ID更新表1中的表2的名称和desc?所以我得到的最终结果是
表1:
id name desc
-----------------------
1 x 123
2 y 345
3 c adf
如何做到这一点:
答案 0 :(得分:74)
对于MySql:
UPDATE table1 JOIN table2
ON table1.id = table2.id
SET table1.name = table2.name,
table1.`desc` = table2.`desc`
对于Sql Server:
UPDATE table1
SET table1.name = table2.name,
table1.[desc] = table2.[desc]
FROM table1 JOIN table2
ON table1.id = table2.id
答案 1 :(得分:21)
Oracle 11g R2:
create table table1 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
create table table2 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');
insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');
merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;
select * from table1;
ID NAME DESC_
---------- ---------- ----------
1 x 123
2 y 456
3 c ghi
答案 2 :(得分:8)
UPDATE table1
SET
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)
答案 3 :(得分:7)
尝试以下代码。它对我有用....
UPDATE TableOne
SET
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT TableTwo.id
FROM TableTwo
WHERE TableOne.id = TableTwo.id)
答案 4 :(得分:1)
使用以下查询块根据ID更新Table1和Table2:
UPDATE Table1, Table2
SET Table1.DataColumn= Table2.DataColumn
where Table1.ID= Table2.ID;
这是解决此问题的最简单,最快捷的方法。