I’m struggling with 3 tables I’m trying to join and exclude certain results.
Basically it’s almost the same as mysql join where not exists, however I still can’t figure out how to combine multiple tables successfully.
The goal is to select results from table A where the row in the intermediate table B is null OR where the table C (linked to B, but not to A) does not match a specific value.
Something like:
SELECT x
FROM tablea
LEFT JOIN tableb
ON tablea.x = tableb.x
LEFT JOIN tablec
ON tableb.y = tablec.y
WHERE tableb.x IS NULL
OR tablec.z != 'excluded'
but it doesn’t work.
I’d also like to avoid subqueries like using NOT IN or NOT EXISTS in order to speed up things… any suggestions?
EDIT: in spite of what I previously said, it should work. Just remember to double check proper braces, nesting and the ‘where’ clauses position when merging multiple joins
This should do the trick with one query and be reasonably fast. 🙂
This is under the assumption that you don’t mind getting rows from tablea where both tableb.x is null and tablec.y is null, or that neither of them are. If you want only rows from tablea where tableb.x OR tablec.y contains values, you need to change the OR to XOR.