首页 新闻 会员 周边

sql 如何比较两表是否有重复值

0
悬赏园豆:10 [待解决问题]

create table #t1(id int,mark char(2))
go
create table #t2(id int,mark char(2))
go
insert into #t1
select 1,'t1' union all
select 2,'t2' union all
select 3,'t3' union all
select 4,'t4'
go
insert into #t2
select 2,'t2' union all
select 7,'t2' union all
select 3,'m3' union all
select 5,'m5' union all
select 6,'t6'
go

 

 

比较mark 的值是否有重复, 比较时要排除id相同的, 比如以上例子中查询结果为:

t1 中id =2的在t2 表中有重复值 ,id=7

 

用INTERSECT 貌似不可以, 只能查询出id相同的

冬天我愛吃火鍋的主页 冬天我愛吃火鍋 | 初学一级 | 园豆:180
提问于:2016-08-29 15:02
< >
分享
所有回答(4)
0

这感觉是两个union到一起,然后groupby就行了?

顾晓北 | 园豆:10844 (专家六级) | 2016-08-29 15:07

我是这样查的 

select * from #t1 a,#t2 b where a.id<>b.id and a.mark=b.mark

结果集:

id mark id mark
2     t2   7   t2

 

但是感觉这种方法好low啊, 所以问问有没有其他高大上的方法

支持(0) 反对(0) 冬天我愛吃火鍋 | 园豆:180 (初学一级) | 2016-08-29 15:10

@宋小熊: 你要那么高大上干嘛?能得到结果就行了呗???

支持(0) 反对(0) 顾晓北 | 园豆:10844 (专家六级) | 2016-08-29 15:30

@顾晓北: 额  好吧  (*^__^*) 嘻嘻……

支持(0) 反对(0) 冬天我愛吃火鍋 | 园豆:180 (初学一级) | 2016-08-29 15:33
1
select t1.id,
    t2.id,
    t1.mark,
    t2.mark
from #t1 t1 
cross join #t2 t2 
where t1.id<>t2.id and t1.mark=t2.mark

 

 

悦光阴 | 园豆:2251 (老鸟四级) | 2016-08-29 15:10

谢谢 嘻嘻 

支持(0) 反对(0) 冬天我愛吃火鍋 | 园豆:180 (初学一级) | 2016-08-29 15:20
0

使用 exists 或 not exists 可以解决

空明流光 | 园豆:106 (初学一级) | 2016-08-30 11:54
0

select * from table group by mark having count(*)>2

从从前有座山 | 园豆:206 (菜鸟二级) | 2016-08-31 16:57
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册