选择表A中不在表B中的列组合

时间:2014-09-22 16:31:10

标签: sql sql-server sql-server-2008

我有两组表,帐户上的所有联系人都有他们的标题等。出于数据迁移的目的,我需要从表A中选择具有表B中不存在的AccountID的所有ContactsIds。它是ContactId和AccountID的组合。我尝试过以下方法:

Select * from Final_Combined_Result wfcr 

 WHERE NOT EXISTS (Select Contact_ID, Account_ID from Temp_WFCR)  

我知道这完全没了,但是我在这里看了几个其他问题但是找不到合适的解决方案。

我也试过这个:

Select * from Final_Combined_Result wfcr  
WHERE NOT EXISTS 
  (Select Contact_ID, Account_ID from Temp_WFCR as tc 
   where tc.Account_ID=wfcr.Account_InternalID 
   AND tc.Account_ID=wfcr.Contact_InternalID)

这似乎是正确的,但我想确定一下。

2 个答案:

答案 0 :(得分:4)

Select wfcr.ContactsId, wfcr.AccountID
from Final_Combined_Result wfcr 
left join Temp_WFCR t_wfcr ON t_wfcr.ContactsIds = wfcr.ContactsId 
                          AND t_wfcr.AccountID = wfcr.AccountID
WHERE t_wfcr.AccountID is null 

请参阅this great explanation of joins

答案 1 :(得分:3)

@ juergend的答案显示了左连接。

使用a not exists加入subselect,它看起来像这样:

Select wfcr.*
from 
  Final_Combined_Result wfcr 
  WHERE NOT EXISTS 
     (Select 1 --select values dont matter here, only the join restricts.
     from 
       Temp_WFCR t
     where t.Contact_ID = wfcr.Contact_InternalID
       and t.account_id = wfcr.Account_InternalID 
     )