Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Combination of columns from Table A not in Table B

I have two sets of table with all the contacts on an Account their titles and etc. For data migration purposes I need to select All ContactsIds with their AccountID from Table A that do not exist in TableB. Its the combination of both the ContactId and the AccountID. I have tried the following:

Select * from Final_Combined_Result wfcr 

 WHERE NOT EXISTS (Select Contact_ID, Account_ID from Temp_WFCR)  

I know this is completely off, but I have looked at a couple of other questions on here but was unable to find an appropriate solution.

I have also tried this:

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)

This seems to be correct but I would like to make sure.

like image 904
user2684009 Avatar asked Oct 28 '25 16:10

user2684009


2 Answers

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 

See this great explanation of joins

like image 136
juergen d Avatar answered Oct 31 '25 05:10

juergen d


@juergend's answer shows the left join.

Using a not exists you join in the subselect, it would look like this:

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 
     ) 
like image 39
crthompson Avatar answered Oct 31 '25 05:10

crthompson