I have 2 mysql tables a and b. I need to show all records in a that are not in b using a common column ‘ID’. Normally this is pretty straight forward but my problem here is this: I need to put a where clause on table b because I’m not interested in all unmatched records just the ones that meet the table 2 where clause criterion:
SELECT a.ID, a.Description FROM a LEFT JOIN b ON a.ID = b.ID WHERE a.Inactive = 0 AND b.Room = '101' AND b.ID Is Null
This returns nothing. However if I remove the AND b.Room = '101'
part, it displays the expected results. But I need that condition because I need only unmatched records specific to a ‘room’ and not all unmatched records
Advertisement
Answer
Move the conditions involving table b
from WHERE to ON clause:
SELECT a.ID, a.Description FROM a LEFT JOIN b ON a.ID = b.ID AND b.Room = '101' WHERE a.Inactive = 0 AND b.ID Is Null
It’ll find rows where a does not have a match in b (id matches and room number = 101).