多表连接问题

印度张三 2009-01-06 11:19:47
有两张表A和B,关联字段为Barcoder,现在要把A表中的AutoID更新到B表中的IDMain中,请写出SQL更新语句
A:
AutoID BarCoder
1 12345
2 56789
B:
IDMain BarCoder
null 12345
null 12345
null 12345
null 56789
null 56789
...全文
35 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
oraclelogan 2009-01-06
  • 打赏
  • 举报
回复
[Quote=引用楼主 yihuaheren 的帖子:]
有两张表A和B,关联字段为Barcoder,现在要把A表中的AutoID更新到B表中的IDMain中,请写出SQL更新语句
A:
AutoID BarCoder
1 12345
2 56789
B:
IDMain BarCoder
null 12345
null 12345
null 12345
null 56789
null 56789
[/Quote]

简单SQL如下,楼主试下吧!
UPDATE B SET IDMain=A.AutoID
FROM A
INNER JOIN B
ON A.BarCoder=B.BarCoder
水族杰纶 2009-01-06
  • 打赏
  • 举报
回复
update B set IDMain=A.AutoID from A inner join B on A.BarCoder=B.BarCoder 
百年树人 2009-01-06
  • 打赏
  • 举报
回复
---测试数据---
if object_id('[A]') is not null drop table [A]
go
create table [A]([AutoID] int,[BarCoder] int)
insert [A]
select 1,12345 union all
select 2,56789
if object_id('[B]') is not null drop table [B]
go
create table [B]([IDMain] int,[BarCoder] int)
insert [B]
select null,12345 union all
select null,12345 union all
select null,12345 union all
select null,56789 union all
select null,56789

---更新---
update B
set IDMain=a.AutoID
from A
where a.BarCoder=b.BarCoder

---查询---
select * from B

---结果---
IDMain BarCoder
----------- -----------
1 12345
1 12345
1 12345
2 56789
2 56789

(所影响的行数为 5 行)
pl_mm 2009-01-06
  • 打赏
  • 举报
回复
update b set idmain=a.autoid
from 表b b left join 表a a on b.barcoder=a.barcoder
百年树人 2009-01-06
  • 打赏
  • 举报
回复
update B
set IDMain=a.AutoID
from A
where a.BarCoder=b.BarCoder
子陌红尘 2009-01-06
  • 打赏
  • 举报
回复
update B set IDMain=A.AutoID from A,B where A.BarCoder=B.BarCoder 

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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