我需要根据两个表中找到的匹配记录更新列数据。 我想更新TABLE2
中NAME列的记录以下是表格
Table1
---------------
Id | Name | color
1 | abc | red
2 | def | green
3 | ghi | blue
Table2
---------------
Id | Name | color |fiedId
1 | abc | red | 1
2 | def | green | 1
3 | ghi | blue | 2
这里table1 ID列是table2中的外键,为fieldId。
所以,我想更新属于这种情况的所有记录
table1.id = table2.fieldId
答案 0 :(得分:1)
听起来你只想要这样的更新:
update table2 t2
set t2.name =
( select t1.name
from table1 t1
where t1.id = t2.fieldid )
关于后续问题:
如果我想设置Name =" xxx"对于所有匹配的行?
update table2 t2
set t2.name = 'xxx'
where t2.fieldid in
( select t1.id from table1 t1 )
或者这可以写成:
update table2 t2
set t2.name = 'xxx'
where exists
( select null from table1 t1
where t1.id = t2.fieldid )
答案 1 :(得分:1)
另一种选择,使用MERGE
:
merge into table2 t2
using (select id, name from table1) x
on (t2.fieldid = x.id)
when matched then update set
t2.name = x.name;
或者,将名称设置为“xxx”:
merge into table2 t2
using (select id from table1) x
on (t2.fiedid = x.id)
when matched then update set
t2.name = 'xxx';