联合主键/复合主键的数据库表,在另一个数据库表是否存在的SQL查询语名

 
  

--如果是只有一个主键的话,就使用主键 not In 、主键 In 来写SQL脚本,很简单就不多说了。
--那联合主键的表又怎么处理呢,其实也很简单,使用Not exists 、exists ,以前还真不知道 exists 还有此用法
--看下面的例子,表@A(字段j,字段n为联合主键),表@B(字段j,字段n为联合主键)

--如果是只有一个主键的话,就使用主键 not In 、主键 In 来写SQL脚本,很简单就不多说了。
--那联合主键的表又怎么处理呢,其实也很简单,使用Not exists 、exists ,以前还真不知道 exists 还有此用法
--看下面的例子,表@A(字段j,字段n为联合主键),表@B(字段j,字段n为联合主键)
declare @A table (i int,j int ,n varchar(50) primary key(j,n))
declare @B table (i int,j int ,n varchar(50) primary key(j,n))
insert @A(i,j,n) 
select 1,1,'a' 
union all select 2,1,'b'
union all select 3,1,'c'
union all select 4,1,'d'
union all select 5,1,'e'
union all select 6,2,'a'
union all select 7,2,'b'
union all select 8,2,'c'
union all select 9,2,'d'
union all select 10,2,'e'

insert @B(i,j,n) 
select 1,1,'a' 
union all select 2,1,'b'
union all select 3,1,'c'
union all select 4,2,'a'
union all select 5,2,'b'
union all select 6,2,'c'

--跟据主键,查询@A表有的,@B没有的
select * from @A a
where not exists( select * from @B b where a.j=b.j and a.n=b.n )
--也可批量删除@A ,跟据主键,@A表有的,@B没有的
delete a from @A a
where not exists( select * from @B b where a.j=b.j and a.n=b.n )
--跟据主键,查询@A表有的,@B也有的
select * from @A a
where exists( select * from @B b where a.j=b.j and a.n=b.n )

转载于:https://www.cnblogs.com/wangzhe/archive/2012/04/25/2469794.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值