龙空技术网

Mysql 使用 group by 不对 null 做分组

小码A梦 607

前言:

如今你们对“mysqlgroup by分组”大体比较关心,你们都想要了解一些“mysqlgroup by分组”的相关文章。那么小编同时在网络上汇集了一些关于“mysqlgroup by分组””的相关内容,希望朋友们能喜欢,小伙伴们一起来了解一下吧!

在项目开发查询数据需要将相同的数据做合并处理,但是字段为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()

在 上看到了一个方法。做分组的时候如果name为null时,对null设置成一个随机值UUID(),这样就避免了null会合并的情况。使用UUID():

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

结果:

标签: #mysqlgroup by分组