2012-06-06 16 views
8

Algo extraño está sucediendo. Tengo un problema con MySQL Community Server 5.1 instalado en Windows NO EN consulta. Cuando hago esta consulta:MySQL "NOT IN" no funciona

select * 
    from table1 
    where date >= "2012-01-01"; 

devuelve 582 filas

select * 
    from table1 
    where date >= "2012-01-01" 
    and the_key in (select some_key from table2); 

devuelve 15 filas

por lo que se puede esperar que la siguiente consulta devolvería 582 - 15 = 567 filas

select * 
from table1 
where date >= "2012-01-01" 
and the_key not in (select some_key from table2); 

devuelve 0 filas

¿Por qué esta última consulta no devuelve ninguna fila?

+1

** clave ** es una palabra clave en SQL intente citarlo con los respaldos –

+2

¿Puede 'some_key' ser nulo? –

+0

Pruebe 'where (date> =" 2012-01-01 ") y (clave no en ...)'; Los documentos de MySQL son vagos en el operador 'not in' y afirman que' expr NOT IN (value, ...) es lo mismo que NOT (expr IN (value, ...)) ', lo que puede dar como resultado' NOT ((date> = "2012-01-01" and key) IN (...)) 'en su caso – lanzz

Respuesta

15

Pruebe esto.

select * 
from table1 
where date >= "2012-01-01" 
and `key` not in (select some_key from table2 where some_key is not null); 

O usando no existe

select * 
from table1 
where date >= "2012-01-01" and not exists (select some_key from table2 where table2.some_key = table1.key 
+0

Bueno, ambos funcionan y parecen ocupar la misma cantidad de tiempo. ¡Gracias! –

+0

@jeffery_the_wind contenta de ayudarte! –

1
select * 
from table1 
where date >= "2012-01-01" 
and `key` not in (select some_key from table2); 
5

Lo más probable es que tiene algunos valores NULL en la columna "clave". Las comparaciones NULL siempre devuelven null, que se evalúa como falso. Esto puede ser contra intuitivo. Por ejemplo

SELECT * FROM MyTable WHERE SomeValue <> 0 

No devolverá los valores con SomeValue = NULL. Aunque intuitivamente, NULL no es igual a cero. Entonces, para arreglar la consulta que tiene, probablemente debería hacer lo siguiente.

select * from table1 where date >= "2012-01-01" 
and (key not in (select some_key from table2) OR key IS NULL);