请问如何合并多张结构相同,而且还有同样关键字记录的表?

TecHunter 2003-11-02 02:42:02
rt
对于关键字相同的记录,要求能够保留或者删除其中一个记录。
谢谢!
...全文
69 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-11-02
  • 打赏
  • 举报
回复
insert dest_table select * from source_table where not exists (select 1 from dest_table where 关键字1=source.关键字1 and 关键字2=source.关键字2)

如果你的主键确实是两个列的话应该不会出错,你贴出错误提示,和你的结构。
TecHunter 2003-11-02
  • 打赏
  • 举报
回复
谢谢大力,我试试!
TecHunter 2003-11-02
  • 打赏
  • 举报
回复
我的关键字是两个字段的组合,应该怎么写?
比如说关键字为:A和B
应该写成:
insert into dest_table select * from source_table where A,B not in (selct 关键字 from dest_table)???
这样好像不对的说。
pengdali 2003-11-02
  • 打赏
  • 举报
回复
两个字段的组合:

insert dest_table select * from source_table where not exists (select 1 from dest_table where 关键字1=source.关键字1 and 关键字2=source.关键字2)
pengdali 2003-11-02
  • 打赏
  • 举报
回复
会,你改为:


insert into dest_table select * from source_table where 关键字 not in (selct 关键字 from dest_table)
TecHunter 2003-11-02
  • 打赏
  • 举报
回复
我现在用的是insert into dest_table select * from source_table
这样的话,source_table如果有关键字和dest_table相同的记录,也会进入到dest_table里面么?这样不是违反了数据库关键字的唯一性?BTW:我的关键字是两个字段的组合。
pengdali 2003-11-02
  • 打赏
  • 举报
回复
删除重复的,只留一条:

alter table 表 add newfield int identity(1,1)

delete 表
where newfield not in(
select min(newfield) from 表 group by 你原来的关键字
)

alter table 表 drop column newfield

34,623

社区成员

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

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