tags:

views:

79

answers:

5

I want to join two tables but I want the result set to only show matches that arent in the right side.

Example:

LeftTable

  • leftID | PK
  • value |

RightTable

  • rightID |PK
  • leftID |FK

    select l.value

    from LeftTable l

    join RightTable r

    on l.leftID = r.leftID

I know this wont give me what I want, but I am just trying to find out which items in the left table DO NOT appear in the right side byusing the leftID foreign key relationship.

Any ideas?

+8  A: 

What if we do

select LT.value
from LeftTable LT
left outer join RightTable RT
on LT.leftID = RT.leftID
Where RT.leftId is null

SO join will return all the matching as well as those rows which are in left but not in right. With where clause we only get those rows for which right table left id is null.

Nitin Midha
Do you think it is good practice to give aliases as **RESERVED** words?
astander
Well, we should never use reserved words. I will change to alias.
Nitin Midha
+1  A: 

select * from LeftTable where leftID not in (select leftID from RightTable)

eliah
+5  A: 

You nearly have it, just a couple of minor changes - the join should be a LEFT JOIN, not an [INNER] JOIN, and you need to only return the rows where the right table is missing, i.e. its fields are NULL:

SELECT T1.value
FROM LeftTable T1
LEFT JOIN RightTable T2
ON T1.leftID = T2.leftID
WHERE T2.leftID IS NULL
Mark Byers
+1 - beat me to it!
davek
Do you think it is good practice to give aliases as **RESERVED** words?
astander
No... I assume the names of the tables have been changed to protect the innocent and that these aren't actually the names used in the production system. I'd certainly *hope* so. But I'll change it anyway.
Mark Byers
+1 for the aliases, otherwise it does not work at all...
astander
@astander: Thanks for pointing it out. :)
Mark Byers
A: 
SELECT LeftID
FROM LeftTable 
    LEFT OUTER JOIN RightTable ON LeftTable.LeftID = RightTable.LeftID
WHERE RightTable.RightId IS NULL
Nathan Koop
A: 

An alternative using exists, as a preference to using where not in. The left outer join with a check on the null state of the right is probably still optimal though.

select
        left.*
    from
        LeftTable as left
    where
        not exists (
            select
                    *
                from
                    RightTable as right
                where
                    right.RightID = left.LeftID
            )
Joe Lloyd