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

一对多更新,但只更新一行
表A: 
Rid productCode 
1 2 
2 1 
A中productCode的值是唯一的 
表B 
id ProductCode Rid 
1 2 需更新的值 
2 1 需更新的值 
3 2 需更新的值

更新后想得到的结果是这样的,因为下面表B productcode的值2出现了二次,但我用表A的值来更新只要更新一次,相同的就不要更新。结果如下所示:
id ProductCode Rid 
1 2 1 
2 1 2 
3 2 null(这里表示空其它空字符也行)

望各位大侠给个实现方法。

------解决方案--------------------
update b
set rid = a.productcode
from tb b ,ta a 
where a.rid = b.productcode and not exists(select 1 from tb where productcode = b.productcode and id < b.id)
------解决方案--------------------
SQL code
------------------------------------
-- Author:%e7%b4%ab%e7%ab%b9%e6%9e%97%e7%95%94 
-- Date:2012-09-11 21:36:56
------------------------------------

-- Test Data: tA
If object_id('tA') is not null 
    Drop table tA
Go
Create table tA(Rid int,productCode int)
Go
Insert into tA
select 1,2 union all
select 2,1 
Go

-- Test Data: tB
If object_id('tB') is not null 
    Drop table tB
Go
Create table tB(id int,ProductCode int,Rid int)
Go
Insert into tB
select 1,2,null union all
select 2,1,null union all
select 3,2,null 
Go
--Start
update b
set rid = a.productcode
from tb b left join ta a on a.rid = b.productcode 
where  not exists(select 1 from tb where productcode = b.productcode and id < b.id)
select * from tb

--Result:
/*

id          ProductCode Rid         
----------- ----------- ----------- 
1           2           1
2           1           2
3           2           NULL

(所影响的行数为 3 行)
*/
--End

------解决方案--------------------
SQL code
;with cet1 as
(select *,Row_number()over(partition by productCode  order by (select 1)) as rn from 表B)update cet1 set Rid  = b.Rid from cet1 a, 表A b  where a.productCode  = b.productCode   and rn = 1

------解决方案--------------------
oracle没update from,更新此点,其他类似就可以了

ls几位辛苦了,呵呵
------解决方案--------------------
SQL code
------------------------------------
-- Author:%e7%b4%ab%e7%ab%b9%e6%9e%97%e7%95%94 
-- Date:2012-09-11 21:36:56
------------------------------------

-- Test Data: tA
If object_id('tA') is not null 
    Drop table tA
Go
Create table tA(Rid int,productCode int)
Go
Insert into tA
select 1,2 union all
select 2,1 
Go

-- Test Data: tB
If object_id('tB') is not null 
    Drop table tB
Go
Create table tB(id int,ProductCode int,Rid int)
Go
Insert into tB
select 1,2,null union all
select 2,2,null union all
select 3,1,null 
Go
--Start
update b
set rid = a.productcode
from tb b left join ta a on a.rid = b.productcode 
where  not exists(select 1 from tb where productcode = b.productcode and id < b.id)
select * from tb

--Result:
/*


id          ProductCode Rid         
----------- ----------- ----------- 
1           2           1
2           2           NULL
3           1           2


*/
--End