多表关联同时更新多条不同的记录方法分享

2020-07-10 08:02:28易采站长站整理

以下为测试例子。
1.首先创建两张临时表并录入测试数据:

create table #temptest1
(
id int,
name1 varchar(50),
age int
)
create table #temptest2
(
id int,
name1 varchar(50),
age int
)


查询出此时的表数据为:


#temptest1                 #temptest2


   


 


2.现在要将#temptest2中的年龄更新到相应的#temptest1中的年龄。


其实就是让[表1]中ID为1的年龄改成19,同时ID为2的年龄改成20。


当然这里的要求是只用一句SQL,不能用循环


结果如下:



 


实现方法如下:


Update t1 


Set t1 .age = t2.age


From  #temptest1 t1


Join #temptest2 t2


On  t1.id = t2.id


 


(补充)Sql Server 2008 Merge命令写法:


merge into #temptest1 t1
using(select age,id from #temptest2) t2
on t1.id = t2.id
when matched then
update set t1.age = t2.age


 


是不是挺有趣的Sql。
如何一次性更新多条不同值的记录
标题可能没说清楚,假设有这样两张表:

create table testA(
id number,
eng varchar2(3),
chi varchar2(3)
)
create table testB(
id number,
eng varchar2(3),
chi varchar2(3),
anythingother varchar2(1)
)

现有记录
testA:
ID ENG CHI
===============
1 a 一
2 b 二
3 c 三
testB:
ID ENG CHI ANY….
=================
1 d 四
2 e 五
3 f 六
我想把testB中的记录的ENG,CHI字段更新到testA中去,以ID来对应。
CODE:
SQL> set autot on
SQL> update ta set ta.b=(select tb.b from tb where ta.a=tb.a) where exists (select 1 from tb where ta.a=tb.a);
已更新4行。
已用时间: 00: 00: 00.01
执行计划
———————————————————-
Plan hash value: 1137212925
——————————————————————————–
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
——————————————————————————–

相关文章 大家在看