今天使用 MySQL 的 not in 进行查询的时候,发现结果里面并没有返回任何数据。SQL 语句没有任何问题,但是结果集却是空,实在无法理解。纠结了半天,最后使用 left join,两表关联,找到了目标数据。但是这样的话,难道 not in 就不能使用了吗?最后经过查找,找到了原因。

mysql 的 not in 中,不能包含 null 值。否则,将会返回空结果集。

对于 not in 来说,如果子查询中包含 null 值的话,那么,它将会翻译为 not in null。除了 null 以外的所有数据,都满足这一点。所以,就会出现 not in “失效”的情况。

例如:我有两张表,t_b_handle 和 t_b_detail,两张表为一一对应关系,两张表通过 t_b_handle 表中的 detail_id 关联。现有查询语句如下:

错误 SQL:

select * from t_b_detail where id not in (

    select detail_id from t_b_handle

)

那么,如果 t_b_handle 表中的 detail_id 存在 null 值,那么这个 SQL 语句就是错误的。返回的结果集就是空的。

如果出现了这个问题,明明应该有数据,而使用 not in 却返回了空集,那么我们可以使用下面的 SQL 来避免这种情况的发生:

正确 SQL:

select * from t_b_detail where id not in (

    select detail_id from t_b_handle where detail_id is not null

)

这样即可解决此问题。


另外,百度百科和另一篇博客里面写的非常好,参考链接如下:




Logo

更多推荐