MySQL 值为Null会导致的问题

MySQL 值为Null会导致的问题

  • 数据准备
select version();
-- 8.0.30

-- 如果存在 person 表先删除
DROP TABLE IF EXISTS person; 

-- 创建 person 表,其中 username 字段可为空,并为其设置普通索引
CREATE TABLE person (
	id INT PRIMARY KEY auto_increment,
	name VARCHAR(20),
	mobile VARCHAR(13),
	index(name)
) ENGINE='innodb';

-- person 表添加测试数据
insert into person(name,mobile) values('Java','13333333330'),
	('MySQL','13333333331'),
	('Redis','13333333332'),
	('Kafka','13333333333'),
	('Spring','13333333334'),
	('MyBatis','13333333335'),
	('RabbitMQ','13333333336'),
	('Golang','13333333337'),
	(NULL,'13333333338'),
	(NULL,'13333333339');
  
select * from person;

count / distinct数据丢失

select count(*),count(name) from person;

-- count(*) count(name)
-- 10       8

select count(distinct name,mobile) from person;
-- 8
-- 当使用count(distinct col1,col2),如果任何一直字段的值为NULL,即使另外一列有值,查询结果也会被忽略

select 数据丢失

如果某列存在 NULL 值时,如果执行非等于查询(<>/!=)会导致为 NULL 值的结果丢失。

select * from person where name<>'Java' order by id;
-- 或
select * from person where name!='Java' order by id;

导致空指针异常

在使用聚会函数,SUM,AVG等,如何值为NULL,查询结果也是NULL,不会是预期值0.

解决方案是 SUM(ifnull(salary, 0))

group by , order by 会统计NULL值

select * from person order by name;

select name from person GROUP by name;