insert into 如何不重复数据

youzheng0079 2008-05-19 04:30:54
现有两表
表a
mid 门店
1 aa
2 bb
3 cc
4 dd
5 ee
6 ff
7 gg
8 hh

表b
mid 门店
1 aa
2 bb
3 cc
7 gg
8 hh
9 ii
10 jj
11 kk
现从表b向表a添加数据.请问如何不会重复添加
想要的结果:
表a
mid 门店
1 aa
2 bb
3 cc
4 dd
5 ee
6 ff
7 gg
8 hh
9 ii
10 jj
11 kk
...全文
1119 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2008-05-19
  • 打赏
  • 举报
回复
--1
insert into A select * from B where 门店 not in (select 门店 from A)
--2
insert into A select * from B where not exists (select 1 from A where mid = B.mid and 门店 = B.门店)
Limpire 2008-05-19
  • 打赏
  • 举报
回复
--> 测试数据: #a
if object_id('tempdb.dbo.#a') is not null drop table #a
create table #a (mid int,门店 varchar(2))
insert into #a
select 1,'aa' union all
select 2,'bb' union all
select 3,'cc' union all
select 4,'dd' union all
select 5,'ee' union all
select 6,'ff' union all
select 7,'gg' union all
select 8,'hh'
--> 测试数据: #b
if object_id('tempdb.dbo.#b') is not null drop table #b
create table #b (mid int,门店 varchar(2))
insert into #b
select 1,'aa' union all
select 2,'bb' union all
select 3,'cc' union all
select 7,'gg' union all
select 8,'hh' union all
select 9,'ii' union all
select 10,'jj' union all
select 11,'kk';

-->如果门店不重复
insert into #a select * from #b where not exists (select 1 from #a where 门店=#b.门店)

select * from #a
/*
mid 门店
----------- ----
1 aa
2 bb
3 cc
4 dd
5 ee
6 ff
7 gg
8 hh
9 ii
10 jj
11 kk
*/
sweetweiwei 2008-05-19
  • 打赏
  • 举报
回复
insert into a select * from b where not exists (select 1 from a where mid=b.mid
lff642 2008-05-19
  • 打赏
  • 举报
回复

--try
insert into a select * from b where mid not in (select mid from a)

Limpire 2008-05-19
  • 打赏
  • 举报
回复
insert into a select * from b where not exists (select 1 from a where mid=b.mid)

22,209

社区成员

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

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