Search code examples
sqlsql-serverinner-join

SQL logic for inner join on (A AND B) OR NOT B


I am looking to do an inner join as follows:

SELECT a.Account
FROM TableA a
JOIN TableB b 
  ON (a.Account = b.Account AND a.Source IN (SELECT Source FROM TableC))
  OR a.Source NOT IN (SELECT Source FROM TableC)

Is there a more simple or efficient way to accomplish this?

Some examples of the data:

TableA (Account, Source):

Account | Source
------------------
111     | florida
222     | florida
333     | georgia
444     | alabama
555     | new York

TableB (Account):

Account
-------
111
222
333

TableC (Source):

Source
-------
florida
alabama

Solution

  • I think that the query can be rewritten by using two left joins and a WHERE clause, to avoid repeating condition a.Source [NOT] IN (SELECT Source FROM TableC):

    SELECT a.Account
    FROM TableA a
    LEFT JOIN TableB b ON a.Account = b.Account
    LEFT JOIN TableC c ON c.Source = a.Source
    WHERE 
        (c.Source IS NOT NULL AND b.Account IS NOT NULL)
        OR c.Source IS NULL
    

    This means: a record in TableA is selected either if both joins succeed, or if the join on TableC did not succed.