求一个更新表的某字段到关联表的另一字段的sql

ronanljy2 2012-03-13 08:33:39
表 a 字段 a1,a2
表 b 字段 b1,a1,b2
关联关系为 a.a1=b.a1
a.a1是主键
现在要把a.a2都赋值成b.b2,求破。
...全文
55 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2012-03-14
  • 打赏
  • 举报
回复
[Quote=引用楼主 ronanljy2 的回复:]
表 a 字段 a1,a2
表 b 字段 b1,a1,b2
关联关系为 a.a1=b.a1
a.a1是主键
现在要把a.a2都赋值成b.b2,求破。
[/Quote]

update a set a2 = b.b2 from a , b where a.a1 = b.a1

update a set a2 = isnull((select b2 from b where b.a1 = a.a1),a2) from a
kaikai_kk 2012-03-13
  • 打赏
  • 举报
回复
这样破?
update a set a2=b.b2 from b where a.a1=b.a1
也可以这样破
update a, b set a.a2=b.b2 where a.a1=b.a1
  • 打赏
  • 举报
回复


go
if OBJECT_ID('a')is not null
drop table a
go
create table a(
id int,
num int
)
go
insert a
select 1,2 union all
select 2,2 union all
select 3,2 union all
select 4,2
go
if OBJECT_ID('b')is not null
drop table b
go
create table b(
id int,
num int
)
go
insert b
select 1,1 union all
select 2,2 union all
select 3,3 union all
select 4,4

update a set num=b.num from b where a.id=b.id

select * from a

/*
id num
1 1
2 2
3 3
4 4
*/
  • 打赏
  • 举报
回复
update a set a2=b.a1 from b where a.a1=b.b2

34,588

社区成员

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

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