日期:2014-05-17  浏览次数:20388 次

请教UPDATE,两个表之间关联更新。!急!!!!!
表A结构:
列a 列b 列c

表B结构:
列a 列m 列n

希望用update,用表A与表B的a列进行关联,把表B的m列用b列填充,n列用c列填充。该如何实现。谢谢!
表A中a列的值都是唯一的。表B中a/m/n三列都存在重复。谢谢!

------解决方案--------------------
SQL code
update 表A
set 列b=(select top 1 m列 from 表B where a列=t.a列),
    列c=(select top 1 c列 from 表B where a列=t.a列)
from 表A t

------解决方案--------------------
SQL code

--> 测试数据: @A
declare @A table (a int,b varchar(1),c varchar(1))
insert into @A
select 1,null,null union all
select 2,null,null union all
select 3,null,null union all
select 4,null,null

--> 测试数据: @B
declare @B table (a int,m varchar(1),n varchar(1))
insert into @B
select 1,'a','j' union all
select 1,'b','k' union all
select 2,'c','l' union all
select 2,'d','m' union all
select 3,'e','n' union all
select 3,'f','o' union all
select 3,'g','p' union all
select 4,'h','q' union all
select 4,'i','r'

--更新前
select * from @A
/*
a           b    c
----------- ---- ----
1           NULL NULL
2           NULL NULL
3           NULL NULL
4           NULL NULL
*/

--更新后
update @A
set b=(select top 1 m from @B where a=t.a),
    c=(select top 1 n from @B where a=t.a)
from @A t

select * from @A
/*
a           b    c
----------- ---- ----
1           a    j
2           c    l
3           e    n
4           h    q
*/