1

I currently have a query

SELECT id FROM table1 WHERE {filters on table1} AND id NOT IN (SELECT table1ID FROM table2 WHERE condition = 0)

Table1 has a 1 - Many relationship with table2 and I'm looking for all the IDs that have no entries in table2 with condition=0.

Is there any way to rewrite this query without the inner select? I'm been scratching my head about it for a while now and any pointers would be welcome.

1 Answer 1

1

You can try something like

SELECT  id 
FROM    table1 t1 LEFT JOIN
        table2 t2   ON  t1.ID = t2.table1ID
                    AND t2.Condition = 0
WHERE   {filters on table1} 
AND     t2.table1ID IS NULL

Or just as good would be

SELECT  id
FROM    table1 t1
WHERE   {filters on table1} 
AND     NOT EXISTS  (
                        SELECT  1
                        FROM    table2 t2
                        WHERE   t1.ID = t2.table1ID
                        ADN     t2.condition = 0
                    )
3
  • Wouldn't that first query have to be an OUTER JOIN? Nov 26, 2010 at 8:22
  • Nope, LEFT JOIN should be fine. You are looking for missing items (thus the IS NULL) and it should only return a single row, as something can only be missing once. Nov 26, 2010 at 8:23
  • Thanks mate, that's perfect. I had something similar to the first one, just couldn't quite get it right. Very much appreciated. Nov 26, 2010 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.