2012-05-30 59 views
2

我有2个表Table1 & Table2均具有比如说10列比较两张表对他们的列

我想这两个表对他们的每一个列值的比较和选择只记录其中有超过三栏比赛 ..

即,

Table1.Col1值与Table2.Col1值匹配
AND Table1.Col2值匹配Table2.Col2价值
Table1.Col3值匹配Table2.Col3

OR

Table1.Col2值与Table2.Col2价值
Table1.Col4值匹配Table2.Col4价值
Table1.Col6Table2.Col6价值等相匹配相匹配。 ..

如何修改迭一个简单而智能的查询呢?

回答

2

加入一个或条件,然后根据匹配的字段数进行筛选(我只能处理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' 

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

+0

你可以把其中一部分直接进入连接的一部分,丢弃在那里的部分 –

+0

我不喜欢这样做,因为它是更一个“过滤器”而不是纯粹的连接条件,但的确,它的工作原理是一样的。 –