数据库重复的问题

Jelindu 2012-08-13 03:54:53
现在有A用户和B用户。
A用户拥有一个ID为1,数量为2的数据。
B用户拥有一个ID为1,数量为4的数据。同时还拥有一个ID为2,数量为2的数据。

现在当某个操作触发后,需要把A用户替换成B用户。并且如果id相同的只能留一条记录数量需要合并。如果id不同,则不变
最后的记录变成
B用户拥有 一个ID为1,数量为6,同时有一个ID为2,数量为2的记录。
共2条数据
...全文
113 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jelindu 2012-08-13
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]
SQL code

declare @id int
set @id=1
if exists (select 1 from B where id=@id)
begin
update B set B.data=B.data+A.data
from B
inner join A
on A.id=B.id and A.id=@id
end
el……
[/Quote]

问题是现在AB重复的记录已经存在了
  • 打赏
  • 举报
回复
declare @id int
set @id=1
if exists (select 1 from B where id=@id)
begin
update B set B.data=B.data+A.data
from B
inner join A
on A.id=B.id and A.id=@id
end
else
begin
insert into B
select * from A where id=@id
end
Jelindu 2012-08-13
  • 打赏
  • 举报
回复
我现在自己想到的办法是先把A用户名UPDATE成用户名B
然后合并数据,最后删掉重复的那条记录。
不过这样要很多条sql语句才能完成。如果这个表很大,就会造成效率低下。
有不有好点的,效率高的办法?

34,587

社区成员

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

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