I am trying to select with a join of a table, then use where to exclude some results, like this:
SELECT * FROM table1
LEFT JOIN table2 ON table1.var = table2.var
WHERE
table1.var IN (select var from table3 WHERE var NOT IN (SELECT var FROM table4))
This is not working. The JOIN is working, but the results are not being reduced for the WHERE subquery. I tried altering the WHERE to WHERE var equals a non-matching value. That successfully filtered the results to 0. Thus, the JOIN with the WHERE works, it just is not working with the subquery.
Help!
3
Answers
I could not get either of the provided solutions to work. I solved the problem, however.
The issue seemed to be whenever I would select * from any joined table. Thus, this version derived from the @SelVazi solution did not work/filter:
Nor did it work (filter) to add * from either of the joined tables, for example:
SOLUTION. What DID work (filter) was to select * from the first table, then select specific columns of other names from joined tables, like this for example:
Adding the selection of all columns from either or both of the joined tables, either the INNER JOINed or LEFT JOINed tables, seemed to override the filtering of the JOINs. In playing with this more, I realized that it is the selection of the joining column (var in this case) in the select for a joined table that specifically caused the issue. Thus, this did not work (filter):
This is not how I have understood the JOINs to work. Perhaps someone can comment to explain. I should also note that var has the same name in table1, table2, table3, and table4 in the database. I wonder if that causes the issue.
It appears that the issue lies with the usage of the subquery in the WHERE clause. To exclude certain results based on a subquery, you can utilize a LEFT JOIN along with NULL values.
According to your query, I think you want data combined by var from table1, table2, and table3, but not not exists in table4. If that’s what you’re after, try this :