【问题标题】:SQL: JOIN problem using temp tables and one columnSQL:使用临时表和一列的 JOIN 问题
【发布时间】:2020-03-12 17:40:18
【问题描述】:

我创建了两个临时表,其中 TABLE1 包含所有项目,而 TABLE2 仅包含 TABLE1 的部分列表。我怎样才能找出表 1 有哪些表 2 没有的部分,反之亦然?请记住,由于 DISTINCT 语句,临时表只有一列。

我确实必须使用联接,但我的想法是,如果我在每个表的各个列上加入,然后在 Where 子句中声明例如第 1 列不等于第 2 列,这是矛盾的。


IF EXISTS   (
            SELECT *
            FROM tempdb.dbo.sysobjects
            WHERE id = Object_id(N'tempdb..#TABLE1')
            )
        BEGIN
            DROP TABLE #TABLE1
        END

IF EXISTS   (
            SELECT *
            FROM tempdb.dbo.sysobjects
            WHERE id = Object_id(N'tempdb..#TABLE2')
            )
        BEGIN
            DROP TABLE #TABLE2
        END
------------------------------------------------
select distinct 1.parts as #TABLE1 from List1 1  --- MAIN LIST

select distinct 2.parts as #TABLE2 from List2 2  --- ADDITIONAL LIST

select *
from #TABLE2 left join
     #TABLE1
     on 2.parts = 1.parts
where 2.parts <> 1.parts 

【问题讨论】:

    标签: sql sql-server join distinct temp-tables


    【解决方案1】:

    您的where 子句正在撤消left join。我会推荐not exists

    select t1.*
    from #table1 t1
    where not exists (select 1 from #table2 t2 where t2.parts = t1.parts);
    

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2014-01-11
      • 1970-01-01
      • 2021-10-24
      • 2018-07-08
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多