I wanted to run a simple query to throw up all the rows of Table1
where a principal column value is not present in a column in another table (Table2
).
I tried using:
SELECT * FROM Table1 WHERE Table1.principal NOT IN Table2.principal
This is instead throwing a syntax error. Google search led me to forums where people were saying that MySQL does not support NOT IN
and something extremely complex needs to be used. Is this true? Or am I making a horrendous mistake?
To use IN, you must have a set, use this syntax instead:
Unfortunately it seems to be a issue with MySql usage of "NOT IN" clause, the screen-shoot below shows the sub-query option returning wrong results:
The subquery option has already been answered, but note that in many cases a
LEFT JOIN
can be a faster way to do this:If you want to check multiple tables to make sure it's not present in any of the tables (like in SRKR's comment), you can use this:
NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL in MySQL
[…]
[…]
[…]
(emphases added)
Be carefull
NOT IN
is not an alias for<> ANY
, but for<> ALL
!http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html
cant' be replaced by
You must use