【问题标题】:sql server compare two column from different tablesql server比较不同表中的两列
【发布时间】:2021-04-24 19:27:15
【问题描述】:

我有两个表,两个表都包含一列

表1 项目

表2 项目

如果 table1 和 table2 的 item 列中的所有值都完全匹配,我想要一个布尔结果 true/false。 例如两个表的列值

item     item
apple    apple
boy      boy
cat      cat

这应该返回 true

item     item
apple    apple
boy      boy
cat      dog

应该返回假

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您只能通过从左到右和从右到左连接两个表来检查记录是否存在于一侧或另一侧。如果有记录不匹配,则为false,否则为true

    select case when exists (
        select top 1 1
        from Table1 t1
        left join Table2 t2 on t2.item = t1.item
        where t2.item is null
        
        union all
    
        select top 1 1
        from Table2 t2
        left join Table1 t1 on t1.item = t2.item
        where t1.item is null
    ) 
        THEN 'false'
        ELSE  'true'
    END as result
    

    【讨论】:

    • 如果项目的顺序发生变化,这将不起作用,这意味着如果我们有苹果,t1 中的男孩和 t2 中的男孩苹果,查询返回 false,它应该返回 true。你能更新一下查询吗
    • 无论项目的顺序如何,这都有效。见sqlfiddle.com/#!18/0f57b/1/0。我更新了查询以匹配您问题中的列名 (item)。
    【解决方案2】:

    您可以使用full join 和聚合:

    select (case when count(*) = 0 then 'true' else 'false' end)
    from t1 full join
         t2
         on t1.item = t2.item
    where t1.item is null or t2.item is null;
    

    这会计算未命中数。如果没有,则表相同。

    或者没有where 子句:

    select (case when count(t1.item) = count(t2.item) then 'true' else 'false' end)
    from t1 full join
         t2
         on t1.item = t2.item
    where t1.item is null or t2.item is null;
    

    注意:与您问题中的数据以及一般问题一样,这假定项目是唯一的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2017-11-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多