2

我有 2 张桌子Table1&Table2都有 10 列

我想将这两个表与它们的每个列值进行比较,并只选择那些有超过三个列匹配的记录..

IE。,

Table1.Col1值匹配Table2.Col1
ANDTable1.Col2值匹配Table2.Col2
ANDTable1.Col3值匹配Table2.Col3

或者

Table1.Col2值匹配Table2.Col2
ANDTable1.Col4值匹配Table2.Col4
ANDTable1.Col6值匹配Table2.Col6值等等...

如何为此编写一个简单而智能的查询?

4

1 回答 1

2

加入 or 条件,然后根据匹配的字段数进行过滤(我只处理了 4 个字段,根据需要添加)。

select *
from table1 t1
join table2 t2
  on t1.field1 = t2.field1 
  or t1.field2 = t2.field2
  or t1.field3 = t2.field3
  or t1.field4 = t2.field4
where 
   ( case when t1.field1 = t2.field1 then 1 else 0 end 
   + case when t1.field2 = t2.field2 then 1 else 0 end 
   + case when t1.field3 = t2.field3 then 1 else 0 end 
   + case when t1.field4 = t2.field4 then 1 else 0 end
   ) >= 3

如果你像我一样懒惰,你可以像这样为所有字段生成语句。

select 'select * ' union all
select '  from table1 t1' union all
select '  join table2 t2' union all
select '    on 1 = 1 ' union all
select '   and t1.' + t1.name + ' = t2.' + t2.name  from sys.columns t1 join sys.columns t2 on t1.name = t2.name where t1.object_id = object_id('table1') and t2.object_id = object_id('table2')
union all
select 'where ( 0' union all
select '   + case when t1.' + t1.name + ' = t2.' + t2.name + ' then 1 else 0 end ' from sys.columns t1 join sys.columns t2 on t1.name = t2.name where t1.object_id = object_id('table1') and t2.object_id = object_id('table2')
union all 
select '      ) >= 3'

(运行查询并复制粘贴结果。)

于 2012-05-30T10:21:28.417 回答