在項目開發查詢數據需要將相同的數據做合並處理,但是字段為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())
結果: