使用另一个表中的数据更新一个表中的行,并根据每一列中的一列相等
根据每个列中相同的一列(user_id)将多行logging从另一个表中更新为一个表。
两个表都有一个user_id
列。 当user_id
列相等时,需要将t2
数据插入到t1
中。
提前感谢您提供的任何帮助。
update table1 t1 set ( t1.column1, t1.column2 ) = ( select t2.column1, t2.column2 from table2 t2 where t2.column1 = t1.column1 ) where exists ( select null from table2 t2 where t2.column1 = t1.column1 );
或者这个(如果t2.column1 <=> t1.column1是多对一的,其中任何一个都是好的):
update table1 t1 set ( t1.column1, t1.column2 ) = ( select t2.column1, t2.column2 from table2 t2 where t2.column1 = t1.column1 and rownum = 1 ) where exists ( select null from table2 t2 where t2.column1 = t1.column1 );
如果你想用t2中的数据更新t1中的匹配行,那么:
update t1 set (c1, c2, c3) = (select c1, c2, c3 from t2 where t2.user_id = t1.user_id) where exists (select * from t2 where t2.user_id = t1.user_id)
“where exists”部分防止在不存在匹配的情况下将t1列更新为null。
merge into t2 t2 using (select * from t1) t1 on (t2.user_id = t1.user_id) when matched then update set t2.c1 = t1.c1 , t2.c2 = t1.c2
如果logging已经存在于t1中(user_id匹配),那么这不是一个插入,除非你很乐意创build重复的user_id。
你可能想要更新?
UPDATE t1 SET <t1.col_list> = (SELECT <t2.col_list> FROM t2 WHERE t2.user_id = t1.user_id) WHERE EXISTS (SELECT 1 FROM t2 WHERE t1.user_id = t2.user_id);
希望能帮助到你…
你总是可以使用和省略“当没有匹配的部分”
merge into table1 FromTable using table2 ToTable on ( FromTable.field1 = ToTable.field1 and FromTable.field2 =ToTable.field2) when Matched then update set ToTable.fieldr = FromTable.fieldx, ToTable.fields = FromTable.fieldy, ToTable.fieldt = FromTable.fieldz) when not matched then insert (ToTable.field1, ToTable.field2, ToTable.fieldr, ToTable.fields, ToTable.fieldt) values (FromTable.field1, FromTable.field2, FromTable.fieldx, FromTable.fieldy, FromTable.fieldz);