玖叶教程网

前端编程开发入门

Mysql 使用 group by 不对 null 做分组

在项目开发查询数据需要将相同的数据做合并处理,但是字段为null,不做合并。

创建表以及添加数据

create table t_student(
       `id` int not null primary key auto_increment,
       `name` varchar(32) ,
       `age` int   
)
insert into t_student(`name`,age) values("aa",11);
insert into t_student(`name`,age) values('bb',12);
insert into t_student(`name`,age) values('cc',13);
insert into t_student(`name`,age) values('cc',14);
insert into t_student(`name`,age) values('cc',15);
insert into t_student(`name`,age) values(null,16);
insert into t_student(`name`,age) values(null,17);

查询数据一共有7条数据

select * from t_student

结果:

再做name合并

select * from t_student group by name

结果:

结果把全部null合并在一起了。

解决方案 使用替换UUID()

https://stackoverflow.com/questions/4588935/group-by-do-not-group-null上看到了一个方法。做分组的时候如果name为null时,对null设置成一个随机值UUID(),这样就避免了null会合并的情况。使用UUID():

select * from t_student group by IFNULL(name,UUID())

结果:

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言