简体   繁体   中英

SQL: JOIN problem using temp tables and one column

I am created two temp tables in which TABLE1 contains all the items and TABLE2 only has the partial list of TABLE1. How can I find out which parts TABLE 1 has that TABLE2 doesn't have or vice versa? Please keep in mind, the temp table only has one column due to the DISTINCT statement.

I do have to use Joins but my thought is if I JOIN on the individual columns of each table and then in the Where clause state that eg column 1 is not equal column 2, it's contradicting.


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 

Your where clause is undoing the left join . I would recommend not exists :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM