根据一张表 update 另一张表的内容..在线等

w78z 2005-08-03 04:42:02
有两张表table1,table2.两表结构一样.
table1;
num age money
111 911 922
222 811 822

table2:
num age money
111 911 922
222 811 822
333 711 722

我的目的是更新table2这张表,将table2内所有num同样也存在在table1中的记录的age,money字段,更新为table1内的对应字段.
比如:table2中有一个num为111,而table1中也有一个num为111,那么,就将table2中num==111的那条记录的age和money,更新成table1中num==111所对应的记录的age和money.
而table2中有一个num=333的,而table1中不存在num==333的,所以就不需要对table2中num==333的记录进行更新..

谢谢各位大虾~~~~
...全文
605 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
filebat 2005-08-03
  • 打赏
  • 举报
回复
--奇奇的方法是对的啊, 而且没有必要做一个表连接!!!
--测试数据
create table table1(num int, age int, [money] int)
insert table1 select 111, 911, 922
union all select 222, 811, 822
create table table2(num int, age int, [money] int)
insert table2 select 111, 811, 922
union all select 222, 811, 722
union all select 333, 711, 722
--更新前
select * from table2

update table2
set age=tt.age, money=tt.money
from table1 as tt
where table2.num=tt.num
--更新后
select * from table2
--清除
drop table table1
drop table table2
hzxiaofeng 2005-08-03
  • 打赏
  • 举报
回复
QQMagicer() 和sunqi_790817(奇奇) 的做法是一样的
hzxiaofeng 2005-08-03
  • 打赏
  • 举报
回复

sunqi_790817(奇奇) 的做法还是有待商榷,在更新时,不能直接写两张表的列名,而from只有一张表,运行时,会找不到a.age,a.money, a.num等字段
update table2 set age = a.age,money = a.money from table1 a where num = a.num

QQMagicer 2005-08-03
  • 打赏
  • 举报
回复
update t
set t.age = s.age,
t.money = s.money
from table2 as t,table1 as s
where t.num = s.num
(t 是目的表,s是源表)
bugchen888 2005-08-03
  • 打赏
  • 举报
回复
楼上都是正解。
summerICEREDTEA 2005-08-03
  • 打赏
  • 举报
回复
update 的from 是什么意思?
冷箫轻笛 2005-08-03
  • 打赏
  • 举报
回复
update t2
set t2.age = t1.age,t2.money = t1.money
from table1 t1 inner join table2 t2
on t1.num=t2.num
vivianfdlpw 2005-08-03
  • 打赏
  • 举报
回复
update table2
set age=table1.age,
[money]=table1.[money]
from table2
join table1
on table2.num=table1.num
sunqi_790817 2005-08-03
  • 打赏
  • 举报
回复
update table2 set age = a.age,money = a.money from table1 a where num = a.num
w78z 2005-08-03
  • 打赏
  • 举报
回复
fasdfsadfsa

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧