如果表table中某列 column_nam存在null值;other_name不存在null值;
1、count()
在进行count(column_name) 会存在数据丢失的问题,解决方案使用:count(*)进行统计
count(*) 会统计值为 NULL 的行,而 count(列名) 不会统计此列为 NULL 值的行。
2、distinct
distinct(column_name,other_name) 数据丢失;other_name 10条数据,结果distinct输出只有8条数据;
3、select数据丢失
进行非等值查询 <> / != 会导致null值的结果丢失:
select * from table where colunm_name<>'Java' order by id;
-- 或
select * from table where colunm_name!='Java' order by id;
解决方案:
在查询结果中拼加上为NULL 值的结果即可
select * from table where colunm_name<>'Java' or isnull(colunm_name) order by id;
4、导致空指针异常
如果某列存在 NULL 值时,可能会导致 sum(column) 的返回结果为 NULL 而非 0,如果 sum 查询的结果为NULL 就可以能会导致程序执行时空指针异常(NPE),我们来演示一下这个问题。
解决方案:
select ifnull(sum(colunm_name), 0) from table where id>4;
5、增加查询难度
当某列值中有 NULL 值时,在进行 NULL 值或者非 NULL 值的查询难度就增加了。所谓的查询难度增加指的是当进行 NULL 值查询时,必须使用 NULL 值匹配的查询方法,比如 IS NULL 或者 IS NOT NULL 又或者是 IFNULL(cloumn) 这样的表达式进行查询,而传统的 =、!=、<>... 等这些表达式就不能使用了,这就增加了查询的难度
错误的使用方法:
select * from table where colunm_name<>null;
select * from table where colunm_name!=null;
正确的用法:
select * from table where colunm_name is not null;
推荐使用:select * from table where !isnull(colunm_name);避免换行之后影响可读性
6、NULL 不会影响索引
我们用 explain 来分析查询计划,colunm_name 中有 NULL 值也不会影响 MySQL 使用索引进行查询。