Search code examples
sqljoinresultset

Compare 3 tables in SQL, with result found in A, B, not C


I am trying to get results from 3 tables, but to show records that reflect Users from A also in B, but not in C

Table A   =   Table B  not in   Table C
-------      --------          --------
UserName     UserName           UserName

I apologize if this is too basic. I'm new at this and could not come up with anything from things I googled.


Solution

  • There are a couple ways you could do this, one would be by using a LEFT JOIN:

    Select      *
    From        TableA  A
    Join        TableB  B   On  A.UserName = B.UserName
    Left Join   TableC  C   On  A.UserName = C.UserName
    Where       C.UserName Is Null;
    

    Another would be by using a WHERE NOT EXISTS:

    Select      *
    From        TableA  A
    Join        TableB  B   On  A.UserName = B.UserName
    Where Not Exists
    (
        Select  *
        From    TableC  C
        Where   C.UserName = A.UserName
    )