Mysql
 SQL >> Database >  >> RDS >> Mysql

NOT IN non restituisce nulla? Trappola NULL e fix NOT EXISTS

Evita NOT IN con una subquery. La sua semantica si rompe appena la subquery restituisce un singolo NULL: il confronto diventa UNKNOWN invece di TRUE per ogni riga, quindi l’intero result set torna vuoto. Nessun errore, nessun warning: solo zero righe, e questo rende il bug costoso da trovare.

Usa invece NOT EXISTS, che è immune al problema:

SELECT p.id, p.name
FROM players p
WHERE p.this = 1
  AND NOT EXISTS (
    SELECT 1 FROM players_online po
    WHERE po.name = p.name AND po.this = 'that'
  )
ORDER BY RAND()
LIMIT 3, 6;

NOT EXISTS è un test di esistenza per riga senza confronto di valore, quindi NULL nella colonna è irrilevante. Tende anche a ottimizzare bene, tipicamente come anti-join. Se devi mantenere NOT IN, aggiungi AND col IS NOT NULL alla subquery, ma NOT EXISTS è l’abitudine migliore.