-1

I have two tables, "Affiliates" and "ControlPanels".

ControlPanels has a field (CP_AffiliateID) that maps to Affiliates (A_ID).

I want to select all records from Affiliates that DO NOT have a match in CP_AffiliateID.

The fields A_ID is a Primary Key so I'm not worried about matching NULL.

What would that join look like?

nbardach
  • 123
  • 1
  • 10
  • 1
    `Affiliates LEFT OUTER JOIN ControlPanels ON A_id = cp_affiliateID WHERE ControlPanels.CP_AffiliateID IS NULL` OR you could do `FROM Affiliates aff WHERE NOT EXISTS (SELECT 1 FROM ControlPanels cp WHERE cp.cp_affiliate_id = aff.a_id)` – JNevill Apr 23 '18 at 19:17
  • @JNevill, THANKS! I don't think it's a dup b/c I'm not concerned with matching on NULL, as A_ID is a Primary Key. HTH. – nbardach Apr 23 '18 at 19:25
  • 1
    @nbardach look more closely at the duplicate and how it relates to your question. Looking for NULL in the `CP_AffiliateID` is absolutely a correct way to do this. It matters not that `A_ID` is a Primary Key. – Tab Alleman Apr 23 '18 at 19:27
  • @Tab Aleman, actually, it's not that I want all records from Affiliates where CP_AffiliateID IS NULL. It's just that if there's is '5' in CP_AffiliateID, I don't want to include the record from Affiliates where A_ID = '5'; – nbardach Apr 23 '18 at 19:28

2 Answers2

2

Please try NOT IN

SELECT * 
FROM   affiliates 
WHERE  affiliates.a_id NOT IN (SELECT cp_affiliateid 
                                  FROM   controlpanels) 
1

You don't really need a join for this and can just use != ALL (subquery).

SELECT * FROM Affiliates A 
WHERE a.A_ID != ALL (SELECT C.CP_AffiliateID FROM ControlPanels C)
Brian
  • 6,717
  • 2
  • 23
  • 31