【问题标题】:compare two tables against their columns比较两个表和它们的列
【发布时间】:2012-06-04 12:37:47
【问题描述】:

我有 2 张桌子 Table1Table2 都有 10 列

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

即,

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

Table1.Col2 值与 Table2.Col2 值匹配
AND Table1.Col4 值匹配 Table2.Col4
AND Table1.Col6 值匹配 Table2.Col6 值等等...

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

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    加入 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'
    

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

    【讨论】:

    • 可以将where部分直接放入join部分,将where部分放下
    • 我不喜欢这样做,因为它更像是一个“过滤器”而不是纯粹的连接条件,但实际上,它的工作原理是一样的。
    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2017-04-22
    • 2013-09-08
    • 1970-01-01
    • 2016-06-01
    相关资源
    最近更新 更多